继承:调用基类的成员和方法

Inheritance : calling members and methods of the base class

本文关键字:成员 方法 基类 调用 继承      更新时间:2023-10-16

我开始理解c++中的继承概念。我们有这样的说法:

派生类继承基类的成员和方法。

因此,我运行以下示例来应用上述语句:

class A {
public:
int a;
A(int val){a=val;}
void afficher(){  cout << a <<endl; }
};
class B : A {
public:
B(int val) : A(val){};
};
int main(){
A a(5);
a.afficher();
B b(6);
b.a = 4;
b.afficher();
return 0;
}

调用成员a时出现以下错误,并且实例bafficher()的方法与语句相矛盾:

error: 'int A::a' is inaccessible
error: 'void A::afficher()' is inaccessible

我的问题:如何通过派生实例调用基类的成员和方法?

与成员一样,使用class关键字声明的类型的基的默认可访问性为private。因此,您的B继承了作为私有成员A的所有内容,因此会出现这些错误。

将其更改为class B: public A.