我有一个 C++ 接口,看起来像这样:
// 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
默认是什么?
struct
和class
之间的唯一区别是,在struct
中,一切都是公开的,除非另有声明,而在class
中,一切都是私有的,除非另有声明。这包括继承。所以class B : A
会默认为私有继承,而struct 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
}