如果一个类总是要被继承,那么让构造函数protected
有意义吗?
class Base
{
protected:
Base();
};
class Child : protected Base
{
public:
Child() : Base();
};
谢谢。
最佳答案
只有在您不希望客户端创建 Base
的实例时才有意义,而是您希望它成为某些 [derived] 类的基类,和/或希望它成为由 Base
的 friend 使用(参见下面的示例)。请记住,protected
函数(和构造函数)只能从派生类和 friend
类中调用。
class Sample;
class Base
{
friend class Sample;
protected:
Base() {}
};
class Sample
{
public:
Sample()
{
//invoking protected constructor
Base *p = new Base();
}
};
关于C++: protected 类构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4524325/