C++构造函数是protect的,子类的普通函数无法访问

我叫侯万楼 2019-07-23 03:58:31
// C++构造函数是protect的,子类的普通函数无法访问,但是子类的构造函数可以访问
class Base
{
protected: // protected
Base()
{
}
Base(const Base& base)
{
}
const Base& operator = (const Base&)
{
}

static void SFun()
{
}

void Fun()
{
}
};

class Son : public Base
{
public:
void Fun()
{
Base *p = new Base(); // error C2248: 'Base::Base': cannot access protected member declared in class 'Base'
Fun(); // OK
SFun(); // OK
}

Son()
{
}
Son(const Son & son)
{
}
};
...全文
484 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
sdghchj 2019-07-24
  • 打赏
  • 举报
回复
protected的构造函数只能在派生类构造函数的初始化列表上进行访问,以对对象本身进行初始化。 其它protected成员函数在派生类中也只能基于派生类去访问。 Protected member access Protected members form the interface for the derived classes (which is distinct from the public interface of the class). A protected member of a class Base can only be accessed 1) by the members and friends of Base 2) by the members and friends (until C++17) of any class derived from Base, but only when operating on an object of a type that is derived from Base (including this) 1. 被Base的成员和友元访问。 2. 被任何派生类对象的成员和友元访问,并且这个仅仅是在操作这个派生类对象时。显然可以看出,只能通过派生类对象调用操作派生类对象,而不能在派生类里独立地去调用基类的构造方法去创建Base对象。
sdghchj 2019-07-24
  • 打赏
  • 举报
回复
https://en.cppreference.com/w/cpp/language/access
我叫侯万楼 2019-07-24
  • 打赏
  • 举报
回复
引用 2 楼 csucxy 的回复:
除非特殊情况,构造函数必须为public,否则无法创建对象,因为创建对象是会调用构造函数,而且这种调用是在类外发生,非public自然不能访问。new操作时会创建一个未命名的对象,构造函数为protected,自然就编译通不过。

构造函数有原因不公有的,我就是疑惑子类的构造函数可以调用父类的构造函数,但是其他普通的函数不行。对于后一点,我觉得你的解释是有道理的。
csucxy 2019-07-23
  • 打赏
  • 举报
回复
除非特殊情况,构造函数必须为public,否则无法创建对象,因为创建对象是会调用构造函数,而且这种调用是在类外发生,非public自然不能访问。new操作时会创建一个未命名的对象,构造函数为protected,自然就编译通不过。
我叫侯万楼 2019-07-23
  • 打赏
  • 举报
回复
Base *p = new Base(); // error C2248: 'Base::Base': cannot access protected member declared in class 'Base' 这儿报错了,编译通不过,求问为啥?

65,180

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧