【问题标题】:Can an instance of object return its own value in c++?对象的实例可以在 C++ 中返回它自己的值吗?
【发布时间】:2019-03-03 14:11:57
【问题描述】:

所以我将 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" 很像析构函数 ~rotating_array 的定义。

似乎应该是面向对象设计的基础。

【问题讨论】:

  • 您是否尝试过为您的班级重载运算符
  • 是的。查找运算符重载

标签: c++ overloading this instance operator-keyword


【解决方案1】:

您应该使用运算符重载

在你的课堂上:

friend ostream& operator<<(ostream& os, const RotatingInt& x)
{
    os << x.value;
    return os;
}

RotatingInt 更改为您的班级名称。

这是一个例子:http://cpp.sh/9turd

【讨论】:

  • 我正在使用运算符重载,但我只想使用实例 x 来返回 x.value(),因此我不必重载所有可能的运算符来访问私有成员“_value”。然后我要重载的是 ++ 和 -- 和 cout >。有点烦人,这对于像“int”这种变体这样的琐碎类来说似乎是不可能的。
  • 我找不到任何关于您所问内容的参考资料,很抱歉。我认为这是不可能的。
  • 不,这似乎不可能。我刚刚编写了 20 多个运算符重载,所有这些都可以用类似“int& ^rotating_array() { return _value; }”的方法来解决,就像定义构造函数或析构函数一样。它很烦人!非常感谢你的帮助。很高兴无论哪种方式都能解决问题。
【解决方案2】:

要做到这一点,C++ 有一些非常有用的东西,但要真正理解它需要付出一些努力。正如 Borgleader 指出的那样:您想要重载

在您的旋转整数类中,您需要告诉编译器运算符

friend std::ostream& operator<<(std::ostream&, const RotatingInteger&)

操作符

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";
}

【讨论】:

  • 不是我想要的,我知道运算符重载,但是像这样的流的链接肯定是有用的信息。非常感谢。
  • 好吧,你可以公开你的实例变量,但这违反了 OOP 的规则。另一种选择是通过创建这样的成员函数来返回实例变量的引用:int&amp; getValue() {return _value;},然后您可以编写x.getValue()++,它会将_value 增加一个。但是您总是需要调用 getValue 函数。如果您不想这样做,恐怕您必须重载所有必要的运算符。
  • 谢谢,这是我令人沮丧的答案——如果有类似“int& rotation_array() { return &_value; }”的东西会很好。哦,谢谢你的帮助。很高兴确切地知道。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-25
相关资源
最近更新 更多