【发布时间】:2011-09-17 19:51:36
【问题描述】:
class Test{
public :
int x;
Test()
{
x = 0;
cout<<"constructor with no arguments called"<<endl;
}
Test(int xx)
{
x = xx;
cout<<"constructor with single int argument called"<<endl;
}
};
int main()
{
Test a(10);
Test aa = 10;
}
输出: 程序编译输出
调用单个 int 参数的构造函数
调用单个 int 参数的构造函数
现在
class Test{
public :
int x;
Test()
{
x = 0;
cout<<"constructor with no arguments called"<<endl;
}
Test(int xx)
{
x = xx;
cout<<"constructor with single int argument called"<<endl;
}
Test( Test& xx)
{
x = xx.x;
cout<<"copy constructor called"<<endl;
}
};
int main()
{
Test a(10);
Test aa = 10;
}
编译失败。
constructorinvokings.cc:36:7: error: no viable constructor copying variable of type 'Test'
Test aa = 10;
^ ~~
constructorinvokings.cc:23:3: note: candidate constructor not viable: no known conversion from 'Test' to 'Test &' for 1st
argument
Test( Test& xx)
^
1 error generated.
我是 C++ 新手。
不是测试 a(10) 并且测试 aa = 10;一样吗?
为什么添加复制构造函数与 Test aa=10 冲突?
如果我将 Test(Test& xx) 修改为 Test(const Test& xx) 它正在工作。但是,当我们尝试使用整数参数调用构造函数时,为什么编译器会检查复制构造函数签名。
请澄清
提前致谢。
【问题讨论】:
-
你使用的是哪个编译器?
标签: c++ initialization copy-constructor