【问题标题】:Overload operator = instead of using accessor重载运算符 = 而不是使用访问器
【发布时间】:2013-12-21 12:48:13
【问题描述】:

我有一个名为 MyInteger 的类,并且这个类有一个 int 类型的数据成员 - 如何重载运算符“=”来返回这个整数?我不允许使用访问器方法返回整数。

数据成员

 private:
    int number;

功能

 int MyInteger::operator=(MyInteger myInteger) {

    myInteger = this->number;

    return myInteger;
}

我知道这是错误的,我尝试进行类型转换,但这也是错误的。

在另一个类中,我使用这个整数只是为了打印

 cout << number << endl;

我该如何解决这个问题?

【问题讨论】:

  • 你想如何使用这个运算符?
  • operator= 按照惯例应该返回*this;。不这样做会立即增加混乱。看起来您更喜欢转换运算符。
  • @sftrabbit - 我编辑了我的问题
  • 你应该为你的班级重载operator&lt;&lt;,而不是让operator=返回MyInteger&amp;以外的东西。

标签: c++ operator-overloading


【解决方案1】:

您要如何使用它的示例根本不使用= 运算符。重载operator= 对您有什么帮助?

如果您希望能够将MyInteger 对象插入到输出流中,则需要overload operator&lt;&lt;,其中左侧操作数是输出流,右侧操作数是您的MyInteger 对象。

【讨论】:

    【解决方案2】:

    我认为您不是指赋值运算符,而是在谈论转换运算符。

    例如:

    #include <iostream>
    #include <algorithm>
    #include <iterator>
    
    class MyInteger
    {
    public:
        MyInteger() : number( 0 ) {}
        void operator ()( int x ) { if ( x < 0 ) ++number; }
        operator int() const { return number; }
    
    private:
        int number;
    };
    
    int main()
    {
       int a[] = { 1, 2, -3, 4, -5, 6, -7 };
       int count = std::for_each( std::begin( a ), std::end( a ), MyInteger() );
       std::cout << "There are " << count << " negative values" << std::endl;
    }
    

    【讨论】:

    • 但请注意,这几乎肯定是个坏主意。你会完全搞乱各种重载的函数调用。更喜欢为std::ostream&amp;MyInteger 定义operator&lt;&lt;
    • @轨道上的轻量级竞赛 我不这么认为,因为据我了解,这门课模拟整数。所以它也可以用于算术运算。此外,我直接回答了这个问题。毫无疑问什么更好。
    • 它可以模拟整数,但它不是整数。它是一个类类型。隐式转换——尤其是到内置类型——是邪恶的!有时直接回答是有害的。当然,在这种情况下,很难说出真正的用例是什么,因为这个特别的例子太做作了,除了包装int之外什么也没做。
    • @Lightness Races in Orbit 你正在尝试完全讨论另一个问题。
    • 你会说话的!该问题要求operator=,您给他一个转换运算符。我们都在寻找他的实际问题并试图给出一个实际解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-05
    • 1970-01-01
    • 2016-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-05
    相关资源
    最近更新 更多