C++运算符重载问题3

在默认情况下,编译器会在每个用户定义的类中重载以下哪些运算符(即使用户尚未编写)?

null
1) Comparison Operator ( == )
2) Assignment Operator ( = ) 

(A) 1和2 (B) 只有一个 (C) 只有两个 (D) 这两个都不是 答复: (C) 说明: 默认情况下,分配运算符在所有用户定义的类中都可用,即使用户尚未实现。默认赋值不进行浅复制。

但是比较运算符“==”没有重载。

#include<iostream>
using namespace std;

class Complex {
private:
    int real, imag;
public:
    Complex(int r = 0, int i =0)  {real = r;   imag = i;}
};

int main()
{
    Complex c1(10, 5), c2(2, 4);

    // For example, below code works fine
    c1 = c2;

    // But this code throws compiler error
    if (c1 == c2)
       cout << "Same";

    return 0;
}

这个问题的小测验

© 版权声明
THE END
喜欢就支持一下吧
点赞8 分享