C++ 中的默认访问修饰符

问题描述 投票:0回答:2

我有一个 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
默认是什么?

c++ inheritance interface access-modifiers modifier
2个回答
2
投票

struct
class
之间的唯一区别是,在
struct
中,一切都是公开的,除非另有声明,而在
class
中,一切都是私有的,除非另有声明。这包括继承。所以
class B : A
会默认为私有继承,而
struct B : A
会默认为公有继承。


2
投票

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
}
© www.soinside.com 2019 - 2024. All rights reserved.