[英]Why can I not instantiate a class whose constructor is private in a friend class?
我有兩節課; Salary
被用來保存關於雇員的工資和信息和計算Employee
有類型的對象class Salary
和像雇員姓名及地址一些成員...
我想要做的是防止class Salary
被實例化,除了class Employee
。 所以我宣稱Salary
的構造函數是私有的,並使Employee
成為Salary
的朋友。 但我得到錯誤:
class Employee; class Salary { public: private: Salary() : revenue_{}, cost_{} {} Salary(int x, int y) : revenue_{ x }, cost_{ y } { } int revenue_, cost_; friend class Employee; }; class Employee { public: std::string name_; Salary sal; }; int main(){ Employee emp{}; // "Salary::Salary()" is inaccessible }
如果我轉發聲明main
問題就會消失:
int main(int, char*[]);
並且在工資中如此制作main
class Salary
的朋友:
class Salary { //... friend int main(int argc, char* argv[]); };
現在程序編譯正確!
***如果我以這種方式聲明一個對象,那么另一件事是主要的:
Employee emp; // ok
Employee emp{}; // error?
因為您沒有為Employee
提供構造函數初始化Employee emp{};
將執行聚合初始化 ,這實質上意味着在main()
的上下文中使用默認規則逐個初始化每個成員。 由於main()
無權訪問Salary
構造函數,因此失敗。
正如其他人指出的那樣,添加一個Employee
默認構造函數將解決您的問題:
class Employee {
public:
Employee() = default;
std::string name_;
Salary sal;
};
您需要Employee
的代理人來打電話給Salary
。 從main
無法獲得Salary
。
例如:
class Employee {
public:
Employee() : sal() {}
public:
std::string name_;
Salary sal;
};
您必須顯式聲明類Employee
的默認構造函數,因此您可以通過uniform initialization
初始化abject:
class Employee {
public:
Employee(){} // add it
std::string name_;
Salary sal;
};
int main(){
Employee emp{}; // now this should compile
}
如果在main()函數中刪除“Employee emp”之后的“{}”,它編譯得很好(Fedora 27上的gcc 7.3.1)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.