|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
- #include<iostream>
- using namespace std;
- class Complex
- {
- private:
- int real;
- int imag;
- public:
- Complex() { real = 0; imag = 0; }
- Complex(int r,int i):real(r),imag(i){ }
- Complex(int r); //转换构造函数声明
- Complex operator+(Complex& c2);
- friend ostream& operator<<(ostream& output, Complex& c2);
- };
- //转换构造函数定义
- Complex::Complex(int r)
- {
- real = r;
- imag = 0;
- }
- Complex Complex::operator+(Complex& c2)
- {
- return(real + c2.real, imag + c2.imag);
- }
- ostream& operator<<(ostream& output, Complex& c2)
- {
- output << "(" << c2.real << "," << c2.imag << "i)";
- return output;
- }
- int main()
- {
- Complex c1(1, 1), c2;
- c2 = c1 + 2;
- }
复制代码
大神们帮忙看一下,声明和定义转换构造函数的时候编译器没报错
定义+的重载也没报错
但是在语句“c2=c1+2"中,编译器提示+用错了
但是我觉得2已经被转换为Complex类了啊应该没错啊
请各位大神指出是哪里做错了
那这个2 是什么时候被转换成Complex的呢。
这个是百度给的关于转换构造函数的解释
说到底! 他还是一个构造函数,你是显示的定义了一个Complex的对象,还是怎么样返回了一个Complex的匿名对象吗。都没有!那这个2,他就只能是个int的字面值!
测试一下转换构造函数怎么才会被调用
- Complex::Complex(int r)
- {
- real = r;
- imag = 0;
- cout << "Complex(int r) function is called!" << endl;
- }
复制代码
1.第一种
- Complex(2);
- Complex c3(2);
复制代码
结果:
第二种:
- Complex Test() {
- return 100;
- }
复制代码
结果:
当然。。还有很多方法。这只是举俩例子
|
|