我看不懂

Cform 2003-06-03 06:43:15
#include <iostream>

using namespace std;

class Foo
{
public:
Foo()
{
cout << "default constructor" << endl;
}

Foo(const Foo &)
{
cout << "copy construction" << endl;
}

~Foo()
{
cout << "destructor" << endl;
}

Foo& operator=(Foo &rhs)
{
cout << "assignment" << endl;
return *this;
}
};


Foo GetAFoo()
{
Foo foo;
return foo;
}


int main()
{
Foo foo1;
Foo foo2;
foo1 = GetAFoo(); // generates compiler error
foo2 = foo1; // compiles OK
return 0;
}



注意:编译时提示错误,我看过答案,说是将一个全局变量赋给了一个临时变量,而临时变量是不可修改的,可我还看不明白到底谁修改了谁?请高手指点。
...全文
58 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
treamboy 2003-06-03
  • 打赏
  • 举报
回复
錯誤是:
[C++ Error] Unit1.cpp(50): E2285 Could not find a match for 'Foo::operator =(Foo)'
如上修改即可.
因上程序採用的是
Foo GetAFoo()
{
Foo foo;
return foo;
}
//上為直接聲明定義一函數其返回對象實體會看作一const
int main()
{
Foo foo1;
Foo foo2;
foo1 = GetAFoo(); //重載操作符=時會出現類型不匹配.Foo& operator=(const Foo &rhs)
foo2 = foo1;
return 0;
}
shenyiwen 2003-06-03
  • 打赏
  • 举报
回复
Foo& operator=(Foo &rhs) => Foo& operator=(const Foo &rhs)

69,371

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧