发个帖子大家一起学习下,下面这段程序,不运行你能说出正确的结果,并解释吗

wxdcxp 2009-09-28 11:57:07

#include <iostream>
using namespace std;
class c
{
public:
c(){i = 0;j = 0;}
c(int x,int y){i = x,j = y;}
c a(c t)
{
cout << "i = " << i << endl;
cout << "t.i = " << t.i << endl;
cout << "j = " << j << endl;
cout << "t.j = " << t.j << endl;
}
private:
int i,j;
};
int main()
{
c t1(1,1),t2(2,2),t3;
t3 = t1.a(t2);
return 0;
}
...全文
114 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
kouwenlong 2009-09-28
  • 打赏
  • 举报
回复
我这里可以通过编译的,不加返回值,最多是个waring。
当然最好加上:
c a(c t)
{
cout << "i = " << i << endl;
cout << "t.i = " << t.i << endl;
cout << "j = " << j << endl;
cout << "t.j = " << t.j << endl;
return *this;
}
aopha 2009-09-28
  • 打赏
  • 举报
回复
i = 1
t.i = 2
j = 1
t.j = 2
forster 2009-09-28
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 oyster2008 的回复:]
代码是通不过编译的,a函数的返回值呢
weixiaoshashou 2009-09-28
  • 打赏
  • 举报
回复
#include <iostream>
using namespace std;
class c
{
public:
c(){i = 0;j = 0;}
c(int x,int y){i = x,j = y;}
c a(c t)
{
cout << "i = " << i << endl;
cout << "t.i = " << t.i << endl;
cout << "j = " << j << endl;
cout << "t.j = " << t.j << endl;
return *this;//这里要返回
}
private:
int i,j;
};
int main()
{
c t1(1,1),t2(2,2),t3;
t3 = t1.a(t2);
return 0;
}
自己运行就有结果了:i=1,t.i=2;j=1,t.j=2;
wanjingwei 2009-09-28
  • 打赏
  • 举报
回复
i = 1
t.i = 2
j = 1
t.j = 2
kouwenlong 2009-09-28
  • 打赏
  • 举报
回复
首先的时候会实例化一个t1对象,并调用构造函数使得i=1,j=1.
然后调用t1的成员函数a(),并传入实参t2对象。
进入函数里,如果不指明,那么数据成员都是t1的,就像i,j。
而向t.i则会调用传入实参的数据成员,就是t2的。
这个实例就是简单的函数调用,感觉没什么特别的地方。
oyster2008 2009-09-28
  • 打赏
  • 举报
回复
代码是通不过编译的,a函数的返回值呢
kouwenlong 2009-09-28
  • 打赏
  • 举报
回复
cout << "i = " << 1 << endl;
cout << "t.i = " << 2 << endl;
cout << "j = " << 1 << endl;
cout << "t.j = " << 2 << endl;

64,654

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

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