【问题标题】:How to return first operand if the second operand of + operator overloading is zero in C++?如果 + 运算符重载的第二个操作数在 C++ 中为零,如何返回第一个操作数?
【发布时间】:2014-01-29 18:19:03
【问题描述】:

我有这个类定义:

class foo{

public:
    foo();
    foo(const int& var);
    foo(const foo& var);
    ~foo();

    const foo operator +(const foo& secondOp) const;

private:
    int a;
    //plus other values, pointers, e.t.c.

};

我还为“+”运算符重载做了这个实现:

const foo foo::operator +(const foo& secondOp) const{

    //I want here to check if i have one operand or two...
    if ((FIRST_OPERAND.a!=0) && (secondOp.a==0)){
        cout << "ERROR, second operand is zero";
        return FIRST_OPERAND;
    }
    else if ((FIRST_OPERAND.a==0) && (secondOp.a!=0)){
        cout << "ERROR, first operand is zero";
        return secondOp;
    }

}

当我写信给main():

foo a(2);
foo b;
foo c;

//I want here to print the ERROR and
//return only the values of a
c = a + b;
  1. 如果第二个操作数为零,我如何return 第一个操作数的值,反之亦然?

【问题讨论】:

  • operator+ 返回一个带有相关信息的任意类型的对象,并仅为该类型重载operator=
  • 如果缺少第二个操作数,您的代码将类似于c = a + ;,对吧?那根本无法编译。
  • 你能说得更具体点吗?有一个代码示例? @0x499602D2
  • operator+() 的第二个操作数永远不会丢失。它从不参与表达式c = a;。在这种情况下,将使用默认生成的分配。
  • @OliCharlesworth 抱歉,我不是那个意思!!让我纠正一下……

标签: c++ operators operator-overloading


【解决方案1】:

你快到了。由于是成员函数,所以第一个操作数是*this,所以将FIRST_OPERAND.a替换为this-&gt;a或者只是a

但是,最好将其设为非成员函数以允许在两个操作数上进行转换(即能够编写 a + 22 + a)。它需要成为朋友才能访问私人成员。

friend foo operator +(const foo& firstOp, const foo& secondOp);

此外,最好不要返回 const 值,因为这会阻止从返回值移动。

【讨论】:

    【解决方案2】:

    检查程序语法正确性的是编译器。无法区分你是否真的要写

    c = a;
    

    就是做作业或者你想写

    c = a + b;
    

    这两种说法都是正确的。

    这是一个所谓的逻辑错误。编译器无法看到我们的想法。

    【讨论】:

      【解决方案3】:

      对于您的c = a; 行,赋值运算符由编译器实现(只是浅拷贝对象内存)。 这就是您的代码“没有第二个操作数”编译的原因。

      如果您希望禁止使用赋值运算符 - 隐藏它。例如。通过使用private 访问修饰符实现。

      【讨论】:

        猜你喜欢
        • 2010-12-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-04-13
        • 2012-09-23
        • 2018-02-11
        • 2013-09-11
        • 2018-01-06
        相关资源
        最近更新 更多