如何在 c++ 中将包含复制构造函数的类的参数构造函数称为私有?



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

我的程序:

#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.请参阅(与您的状态无关,但只是为了了解更多信息):为什么受保护的构造函数在此代码中引发错误?

最新更新