铁锈_ 2017-07-16 07:35 采纳率: 0%
浏览 889

C++显式调用构造函数初始化对象有用到拷贝构造函数么?

作者:大漠刀客
链接: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;
}
  • 写回答

2条回答

  • watl0 2017-07-16 10:38
    关注

    拷贝构造被调用的三个条件
    1.对象拷贝(A a;B b(a))
    2.对象作为参数传值
    3.对象作为函数返回值被赋值给左值

    评论

报告相同问题?

悬赏问题

  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?