作者:大漠刀客
链接:https://www.nowcoder.com/discuss/29421
来源:牛客网
下面代码中的HasPtr hp4 = HasPtr(1,str);
这里有用到拷贝构造函数,拷贝构造函数中的语句“调用拷贝构造函数”
并没有输出。
但是将拷贝构造函数中的const去掉变成HasPtr( HasPtr& hp)又报错了,
拷贝构造函数中的第一个参数必须是引用类型,但未必是const吧?
而且从正确使用时的输出看,这里拷贝构造函数HasPtr( const HasPtr& hp)并没有调用啊
#include <iostream>
#include <memory>
using std::string;
using std::cout;
using std::endl;
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;
}
int i;
string *ps;
};
int main( ){
string str = "hello";
HasPtr hp4 = HasPtr(1,str);
cout<<hp4.i<<" "<<hp4.ps<<endl;
return 0;
}