[英]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.