所以我将int的变体定义为旋转整数类,这非常简单,但我希望能够做类似的事情
cout << x << '\n';
而不是 :
cout << x.value() << '\n';
这是可能吗?
什么都没有
class rotating_int
{
private:
int _value, _low, _high;
public:
int operator++(int) { if (++_value > _high) _value = _low; return _value; }
int operator--(int) { if (--_value < _low) _value = _high; return _value; }
int operator++() { if (++_value > _high) _value = _low; return _value; }
int operator--() { if (--_value < _low) _value = _high; return _value; }
void operator=(int value) { _value = value; }
int operator==(int value) { return _value == value; }
int val() { return _value; }
rotating_int(int value, int low, int high) { _value = value; _low = low; _high = high; }
int ^rotating_array() { return &_value; }
};
其中“^ rotating_array”非常类似于析构函数~roting_array的定义。
似乎应该是面向对象设计的基础。
您应该使用运算符重载。
在课堂上:
friend ostream& operator<<(ostream& os, const RotatingInt& x)
{
os << x.value;
return os;
}
将RotatingInt
更改为您的班级名称。
这是一个例子:http://cpp.sh/9turd
要做到这一点,C ++有一些非常有用的东西,但要真正理解它需要一些努力。正如Borgleader所示:你想要重载<<运算符。
在你的旋转整数类中,你需要告诉编译器运算符<<(这是编译器在看到任何对象的<<运算符时调用的函数的方式)可以访问类的私有成员。这是通过使函数成为旋转整数类的友元函数来完成的。在您添加的课程中:
friend std::ostream& operator<<(std::ostream&, const RotatingInteger&)
operator <<函数的实现可能如下所示:
std::ostream& operator<<(std::ostream& os, const RotatingInteger& i) {
os << i.value;
return os; // you need to return the stream in order to add something
// else after you pass the RotatigInteger-object like in your
// example: cout << x << "\n";
}