【问题标题】:How to call a parameter constructor of a class that contains a copy constructor as private,in c++?如何在c ++中调用包含私有复制构造函数的类的参数构造函数?
【发布时间】:2017-08-17 05:34:27
【问题描述】:

我有一个由参数化构造函数组成的类,我需要在创建对象时调用它。该类还包含一个私有复制构造函数,限制为它创建一个对象。现在如何调用这个类的参数构造函数。我认为我们可以创建一个指向该类的指针引用。但是如何使用引用调用参数构造函数呢?

我的计划:

#include<iostream>
#include<string>
using namespace std;

class ABase
{
protected:
    ABase(string str) {
        cout<<str<<endl;
        cout<<"ABase Constructor"<<endl;
    }
    ~ABase() {
    cout<<"ABASE Destructor"<<endl;
    }
private:
    ABase( const ABase& );
    const ABase& operator=( const ABase& );
};


int main( void )
{
    ABase *ab;//---------How to call the parameter constructor using this??

    return 0;
}

【问题讨论】:

    标签: c++ constructor copy-constructor


    【解决方案1】:

    您需要的语法是ABase *ab = new ABase(foo);,其中foostd::string 实例或std::string 可以构造的东西,例如const char[] 文字,例如"Hello".

    别忘了调用delete释放内存。

    (如果您不需要指针类型,也可以写成ABase ab(foo)。)

    【讨论】:

    • 个人,我更希望看到const auto ab = std::make_unique&lt;ABase&gt;(foo);(换句话说,使用std::unique_ptr,让make_unique为你隐藏new。)
    【解决方案2】:

    你不能这样做。因为你的 ctor 是protected。请看(与您所在州无关,仅供了解):Why is protected constructor raising an error this this code?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-19
      • 1970-01-01
      • 2016-12-09
      • 2011-02-08
      • 2019-08-07
      • 1970-01-01
      • 2012-06-17
      • 1970-01-01
      相关资源
      最近更新 更多