2017-03-24 137 views
0

我有一個類,它包含一個參數化構造函數,我需要在創建對象時調用它。該類還包含一個私人拷貝構造函數,以限制爲它創建一個對象。現在如何調用這個類的參數構造函數。我想我們可以創建一個指向類的指針。但如何使用參考調用參數構造函數?如何在C++中調用一個包含拷貝構造函數的類的參數構造函數爲private?

我的計劃:

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

回答

1

你需要的語法是ABase *ab = new ABase(foo);其中foo要麼是std::string實例或東西,std::string可以承擔建築,如const char[]文字,例如"Hello"

不要忘記撥打delete來釋放內存。

(或者你可以寫ABase ab(foo)如果你不需要指針類型。)

+0

*個人*,我寧願看到'const auto ab = std :: make_unique (foo);'(換句話說使用std :: unique_ptr,讓'make_unique'爲你隱藏'new'。) –