【问题标题】:Why VC++ compiler gives error on compound operator overloading?为什么 VC++ 编译器在复合运算符重载时出错?
【发布时间】:2014-09-05 20:02:39
【问题描述】:

我正在努力学习C++。而且我有一些运算符重载函数,如下所示(我取自 The C++ Programming Language 第 76 页,第 76 页):

complex& operator+=(complex z) { re += z.re; im += z.im; return *this; } // add to re and im
// and return the result
complex& operator−=(complex z) { re  -= z.re; im -= z.im; return *this; }
complex& operator*=(complex); // defined out-of-class somewhere
complex& operator/=(complex); // defined out-of-class somewhere

+= 重载工作正常,但对于 -=,我得到 10 编译器错误:

如果我删除 = 并重载 - 运算符,它会编译。是什么原因 ?我想知道我做错了什么?我尝试了几种组合,清除 - 重建解决方案,重新启动 Visual Studio,但它们不起作用。

注意:我使用的是 Visual Studio 2013,并且我已经安装了 Visual C++ Compiler November 2013 CTP

这是完整的类定义:

class complex{
     double re, im;
     // representation: two doubles
public:
    complex(double r, double i) :re{ r }, im{ i } {} // construct complex from two scalars
    complex(double r) :re{ r }, im{ 0 } {} // construct complex from one scalar
    complex() :re{ 0 }, im{ 0 } {} // default complex: {0,0}
    double real() const { return re; }
    void real(double d) { re = d; }
    double imag() const { return im; }
    void imag(double d) { im = d; }
    complex& operator+=(complex z) { re += z.re; im += z.im; return *this; } // add to re and im
    // and return the result
    complex& operator−=(complex z) { re  -= z.re; im -= z.im; return *this; }
    complex& operator*=(complex); // defined out-of-class somewhere
    complex& operator/=(complex); // defined out-of-class somewhere
};

【问题讨论】:

  • 附带说明,最好让您的操作员使用const complex&。就像现在一样,当您调用操作员时,正在复制给定的复合体,这是一种浪费。

标签: c++ visual-studio operator-overloading


【解决方案1】:

在令牌-= 中似乎还有一些其他符号(似乎取而代之的是减号)

operator−=(

重新输入令牌-= 或从我的帖子中复制整行。:)

complex& operator-=(complex z) { re  -= z.re; im -= z.im; return *this; }

【讨论】:

  • 无论如何,这是因为我不是编译器,我从 .pdf 文件中复制/粘贴了代码(因为我的懒惰)。从现在开始,不再复制/粘贴:)
  • @Selman22 是的,很明显有一些印刷符号。
【解决方案2】:

几件事:

  • 除了每个初始值设定项的大括号外,您的构造函数都没有问题。大括号仅用于以逗号分隔的成员初始化器列表之后的代码块,如下所示:

complex(double r, double i) :re(r), im(i) {}

  • 其次,operator-= 部分中似乎有一些奇怪的字符。它看起来不错,但是当我粘贴它时无法编译。我刚刚重新输入了operator-= 和 zip,它起作用了。

【讨论】:

  • 第二个是正确的,但是大括号工作正常,我不确定,但我认为它们是 c++11 中的新功能?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-12-18
  • 1970-01-01
  • 1970-01-01
  • 2023-03-13
  • 2014-11-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多