c++ - C++ 中的继承成员函数如何处理子成员变量?

标签 c++ inheritance

例如,我有基类 A:

class A {
public:
    callA() {
        val = 100;
        std::cout << this->val << std::endl;
    }
    int val;
}

class B : public A {
    public:
    B() {
        val = 10;
    }
    int val;
}

B b;
b.callA();

b.callA() 会打印什么?

对于 B 继承 A,如果 B 没有字段 val,B 会共享一个对 A 的 val 的精确引用,还是一个拷贝?

最佳答案

在内部,B 类的任何实例都包含 A 类的完整拷贝。事实上,当您初始化 B 类的新实例时,A 类的构造函数首先运行。因此,当您从基类调用非虚函数时,它将像从派生类内部的基类运行一样运行。它甚至可以访问基类的私有(private)变量(派生类无法访问,它只能访问基类的公共(public)/ protected 变量)。

Example :

#include <iostream>
using namespace std;

class A
{
public:

   A()
   {
      cout << "Base constructor!" << endl;

      privateVar = 10;
   }

   void testPrint()
   {
      cout << "privateVar: " << privateVar << endl;
   }

private:

   int privateVar;
};

class B : public A
{
public:
   B()
   {
      cout << "Derived Constructor!" << endl;
   }
};

int main()
{
   B testB;
   testB.testPrint();

   return 0;
}

关于c++ - C++ 中的继承成员函数如何处理子成员变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31921580/

相关文章:

c++ - 如何在 C/C++ 中处理 unicode 字符序列?

c++ - Qt4:在操作 QGraphicsItem 时将鼠标光标锁定到位

c++ - 为什么范围解析不适用于重写变量?

c++ - 私有(private)/保护变量 "error: within this context"

c++ - 类数学 vector 操作的自动符号约定

c++ - 成员函数指针

C++:继承和运算符重载

c# - 如何让子类实现接口(interface)?

c++ - 需要在后代 .h 文件中重新声明被覆盖的函数

python - 在 python 中从 str 或 unicode 继承时是否有可能在分配后保留类实例?