看到网络上面一句描述:在一个类中定义了全部是默认参数的构造函数的后,不能再定义重载构造函数
感觉会有歧义,其实看怎么理解了。应该还是可以定义拷贝构造函数或更多参数的构造函数的,
只要在构造函数的选择上不会有二义性就可以
如下:
#include <stdio.h>
class Test
{
private:
int i;
int j;
int* p;
public:
int getI()
{
return i;
}
int getJ()
{
return j;
}
int* getP()
{
return p;
}
Test(const Test& t)
{
i = t.i;
j = t.j;
p = new int;
*p = *t.p;
}
Test(int v=0,int x=0,int y=0)
{
i = x;
j = y;
p = new int;
*p = v;
}
Test(int v,int x,int y,int z)
{
i = x;
j = y+z;
p = new int;
*p = v;
}
void free()
{
delete p;
}
};
int main()
{
Test t1(1,2,3,4);
Test t3(10,20,30);
Test t2(t3);
printf("t1.i = %d, t1.j = %d, *t1.p = %d
", t1.getI(), t1.getJ(), *t1.getP());
printf("t2.i = %d, t2.j = %d, *t2.p = %d
", t2.getI(), t2.getJ(), *t2.getP());
t1.free();
t2.free();
return 0;
}
运行结果:
t1.i = 2, t1.j = 7, *t1.p = 1
t2.i = 20, t2.j = 30, *t2.p = 10