鍍金池/ 問答/C++/ C++ private 構(gòu)造函數(shù) 以及 friend 類 問題

C++ private 構(gòu)造函數(shù) 以及 friend 類 問題

// account.h
class Account
{
    friend class std::vector<Account>;
public:
    Account(const char *, double = 0.0);
 
private:
    Account(){};
};

書上說 Account 的成員函數(shù)及其友元 vector 可以用任何一個構(gòu)造函數(shù)來定義 Account 對象;
那我在 main.c 中

vector<Account> v1(10);

為什么會是錯的?
那我要怎么正確使用才體現(xiàn)出 vector 的友元性呢?

回答
編輯回答
離夢

由于你沒有給出錯誤提示,無法判斷錯誤的具體原因。

考慮到Account只授予了std::vector<Account>訪問權(quán)。一個可能得原因是在std::vector<Account>內(nèi)對Account的構(gòu)造是由另一個類/函數(shù)完成的,比方說std::allocator<Account>。

class Account
{
    friend std::vector<Account>::allocator_type;
public:
    Account(const char *, double = 0.0);
private:
    Account() {}
};
2017年9月10日 00:19