为什么是这样输出的呢?

来源:百度知道 编辑:UC知道 时间:2024/05/30 05:04:58
#include <iostream>
using namespace std;
class Test
{
public:
int p1;
public:
Test(int temp)
{
p1=temp;
}
Test(Test &o)
{
o.p1 = this->p1;
}
};
void main()
{
Test a(255);
Test b=a;
cout<<b.p1;
cin.get();
}
我用的是c++builder 6.0
问题1:我用Test(int &temp)就提示[C++ Error] ch12_7.cpp(19): E2285 Could not find a match for 'Test::Test(int)',为什么?
问题2.当我改回上式子时,输出结果是256,而不是255,为什么呢?
还有Test b=a;应该是Test b(a);
为什么是Test b(a);
难道不能直接复制吗?我用直接的方式可以得出正确的结果!

你的拷贝构造函数有问题,应该是this->p1 = o.p1;
还有Test b=a;应该是Test b(a);
我跑过了,这两个改掉就好了。
Test b=a;如果要这么写,就得实现Test& operate=(const Test& other)这个方法。

可能是你的C++Builder编译器的问题,这段程序把
o.p1 = this->p1改成this->p1=o.p1
在我的电脑上运行是没问题的,输出就是255.

编译环境:VC6.0 WinXP