大河之jian 发表于 2020-3-29 14:33:56

重载运算符参数加const

/*求复数相加*/
#include<iostream>
using namespace std;
class Complex
{
        public:
                Complex()
                {
                        real=0;
                        imag=0;
                }
                Complex(double t,double d)
                {
                        real=t;
                        imag=d;
                }
               
                Complex operator +(const int &x);         /*不加const显示编译错误*/
       
                void display()
                {
                        cout<<"("<<real<<","<<imag<<"!)"<<endl;
                }
        private:
                double real;
                double imag;
};
Complex Complex::operator +(const int &x)            /*不加const显示编译错误*/
{
        return Complex(real+x,imag);
}
int main()
{
        Complex t1(3.4,5.2);
        Complex t3,t4;
        t3=t1+2;
        t3.display();
        return 0;
}
不加const编译通不过,这是为什么呢,我也不需要改变int的值呀

time1970 发表于 2020-3-29 14:36:45

不应该的,看你编译器,你的编译器错误信息是什么

人造人 发表于 2020-3-29 14:41:38

#include<iostream>
using namespace std;
class Complex
{
      public:
                Complex()
                {
                        real=0;
                        imag=0;
                }
                Complex(double t,double d)
                {
                        real=t;
                        imag=d;
                }
               
                Complex operator +(int &x);         /*不加const显示编译错误*/
      
                void display()
                {
                        cout<<"("<<real<<","<<imag<<"!)"<<endl;
                }
      private:
                double real;
                double imag;
};
Complex Complex::operator +(int &x)            /*不加const显示编译错误*/
{
      return Complex(real+x,imag);
}
int main()
{
      Complex t1(3.4,5.2);
      Complex t3,t4;
      //t3=t1+2;                // 是这里导致的,加const就是为了这里
        int a = 1234;
        t3 = t1 + a;
      t3.display();
      return 0;
}

大河之jian 发表于 2020-3-29 14:42:54

time1970 发表于 2020-3-29 14:36
不应该的,看你编译器,你的编译器错误信息是什么

c.cpp(35) : error C2679: binary '+' : no operator defined which takes a right-hand operand of type 'const int' (or there is no acceptable conversion)
执行 cl.exe 时出错.
声明和下面定义都不加const会显示如上错误

人造人 发表于 2020-3-29 14:44:13

#include <iostream>

int main()
{
        int a = 1234;
        int &r1 = a;
        //int &r2 = 1234;        // 这个就不行
        const int &r3 = 1234;        // 没问题
      return 0;
}

time1970 发表于 2020-3-29 14:57:03

大河之jian 发表于 2020-3-29 14:42
c.cpp(35) : error C2679: binary '+' : no operator defined which takes a right-hand operand of type ...

楼下正解,引用只能对左值,常引用才可以引用右值
页: [1]
查看完整版本: 重载运算符参数加const