问题描述
// A.h
#pragma once
class A
{
public:
//Some declarations.
private:
//Some declarations.
protected:
//Some declarations.
};
具体形式并不重要。由于这是一个接口,因此会有一个类 B
继承自 A
。在类 B
的头文件中,我有:
// B.h
#pragma once
class B : A
{
public:
//Some declarations.
private:
//Some declarations.
protected:
//Some declarations.
};
我担心的是我倾向于使用 class B : A
而不是 class B : public A
,只是我记性不好。
到目前为止我没有遇到任何问题,因为它是一个足够小的项目。但是忘记 public
关键字会在任何意义上影响我的项目吗?
或者更简洁地说,我知道访问修饰符的工作原理,但是 class B : A
默认是什么?
解决方法
class B : A
默认是什么?
class B : private A { /*...*/ }
但是忘记 public 关键字会在任何意义上影响我的项目吗?
是的。别忘了。
考虑以下事项:
// A.h
class A {
public:
void f(){}
};
// B.h
class B : A {};
int main() {
B b;
b.f(); // f is inaccessible because of private inheritance
}
,
struct
和 class
之间的唯一区别在于,在 struct
中,除非另有声明,否则一切都是公开的,而在 class
中,除非另有声明,否则一切都是私有的.这包括继承。所以 class B : A
将默认为私有继承,而 struct B : A
将默认为公共继承。