从子类方法访问基类变量

Access Base class variable from child class method

本文关键字:基类 类变量 访问 类方法      更新时间:2023-10-16

如何从子方法访问基类变量?我有一个分割错误。

    class Base
    {
    public:
        Base();
        int a;
    };
    class Child : public Base
    {
    public:
        void foo();
    };
    Child::Child() :Base(){
    void Child::foo(){
        int b = a; //here throws segmentation fault
    }

在另一个类别中:

    Child *child = new Child();
    child->foo();

公开类变量不是一个好的做法。如果你想从Child访问a,你应该有这样的东西:

class Base {
public:
  Base(): a(0) {}
  virtual ~Base() {}
protected:
  int a;
};
class Child: public Base {
public:
  Child(): Base(), b(0) {}
  void foo();
private:
  int b;
};
void Child::foo() {
  b = Base::a; // Access variable 'a' from parent
}

我也不会直接访问a。如果您为a制作一个publicprotected getter方法会更好。

class Base
{
public:
    int a;
};
class Child : public Base
{
    int b;
    void foo(){
        b = a;
    }
};

我怀疑你的代码是否编译过!

问题是我从一个尚未存在的对象调用Child::foo()(通过信号和插槽连接)。