C++显式调用构造函数创建对象无法正确匹配构造函数?
HasPtr hp4 = HasPtr(1,str);一开始我忘记把拷贝构造函数第一个参数设置为const了,HasPtr(const HasPtr& hp)写成了HasPtr(HasPtr& hp)结果出错,
可我觉得这和初始化hp4是没有关系的啊,我想调用的构造函数是HasPtr( int i1,string &str )
程序代码:
#include <iostream> #include <memory> using namespace std; class HasPtr{ public: HasPtr() = default; HasPtr( int i1,string &str ){ i = i1; ps = &str; } HasPtr(const HasPtr& hp){ i = hp.i; ps = new string( *hp.ps ); cout<<"调用拷贝构造函数"<<endl; } HasPtr& operator=( HasPtr& hp){ cout<<"调用拷贝赋值运算符"<<endl; i = hp.i; ps = hp.ps; return *this; } int i; string *ps; }; int main( ){ string str = "hello"; HasPtr hp4 = HasPtr(1,str); cout<<hp4.i<<" "<<hp4.ps<<endl; HasPtr hp1(1,str); cout<<"hp1建立完成"<<endl; HasPtr hp2 = hp1; HasPtr hp3; hp3 = hp1; HasPtr* hp5 = new HasPtr(1,str); return 0; }