如何在 C++ 中将包含复制构造函数的 class 的参数构造函数调用为私有?

How to call a parameter constructor of a class that contains a copy constructor as private,in c++?

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

我的程序:

#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;
}

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

别忘了调用delete释放内存。

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

你不能这样做。因为你的ctor是protected。请参阅(与您的状态无关,但仅用于了解更多信息):Why is protected constructor raising an error this this code?