鱼C论坛

 找回密码
 立即注册
查看: 1344|回复: 2

[已解决]转换构造函数无法正常使用

[复制链接]
发表于 2020-9-13 15:00:11 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
  1. #include<iostream>

  2. using namespace std;

  3. class Complex
  4. {
  5. private:
  6.         int real;
  7.         int imag;
  8. public:
  9.         Complex() { real = 0; imag = 0; }
  10.         Complex(int r,int i):real(r),imag(i){ }

  11.         Complex(int r); //转换构造函数声明

  12.         Complex operator+(Complex& c2);
  13.         friend ostream& operator<<(ostream& output, Complex& c2);
  14. };

  15. //转换构造函数定义
  16. Complex::Complex(int r)
  17. {
  18.         real = r;
  19.         imag = 0;
  20. }

  21. Complex Complex::operator+(Complex& c2)
  22. {
  23.         return(real + c2.real, imag + c2.imag);
  24. }

  25. ostream& operator<<(ostream& output, Complex& c2)
  26. {
  27.         output << "(" << c2.real << "," << c2.imag << "i)";
  28.         return output;
  29. }

  30. int main()
  31. {
  32.         Complex c1(1, 1), c2;
  33.         c2 = c1 + 2;
  34. }
复制代码

大神们帮忙看一下,声明和定义转换构造函数的时候编译器没报错
定义+的重载也没报错
但是在语句“c2=c1+2"中,编译器提示+用错了
但是我觉得2已经被转换为Complex类了啊应该没错啊
请各位大神指出是哪里做错了
最佳答案
2020-9-13 16:17:00
那这个2 是什么时候被转换成Complex的呢。

这个是百度给的关于转换构造函数的解释
转换构造函数.png
说到底! 他还是一个构造函数,你是显示的定义了一个Complex的对象,还是怎么样返回了一个Complex的匿名对象吗。都没有!那这个2,他就只能是个int的字面值!

测试一下转换构造函数怎么才会被调用

  1. Complex::Complex(int r)
  2. {
  3.     real = r;
  4.     imag = 0;

  5.     cout << "Complex(int r) function is called!" << endl;
  6. }
复制代码


1.第一种
  1.     Complex(2);
  2.     Complex c3(2);
复制代码


结果:
demo1.png

第二种:
  1. Complex Test() {

  2.     return 100;
  3. }
复制代码


结果:
demo2.png

当然。。还有很多方法。这只是举俩例子
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2020-9-13 16:17:00 | 显示全部楼层    本楼为最佳答案   
那这个2 是什么时候被转换成Complex的呢。

这个是百度给的关于转换构造函数的解释
转换构造函数.png
说到底! 他还是一个构造函数,你是显示的定义了一个Complex的对象,还是怎么样返回了一个Complex的匿名对象吗。都没有!那这个2,他就只能是个int的字面值!

测试一下转换构造函数怎么才会被调用

  1. Complex::Complex(int r)
  2. {
  3.     real = r;
  4.     imag = 0;

  5.     cout << "Complex(int r) function is called!" << endl;
  6. }
复制代码


1.第一种
  1.     Complex(2);
  2.     Complex c3(2);
复制代码


结果:
demo1.png

第二种:
  1. Complex Test() {

  2.     return 100;
  3. }
复制代码


结果:
demo2.png

当然。。还有很多方法。这只是举俩例子
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 1 反对 0

使用道具 举报

 楼主| 发表于 2020-9-13 16:56:14 | 显示全部楼层
风过无痕丶 发表于 2020-9-13 16:17
那这个2 是什么时候被转换成Complex的呢。

这个是百度给的关于转换构造函数的解释

好的,谢谢啦
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-7-4 16:12

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表