在超类中定义但在子类中实现的方法:访问子类属性?

Method defined in superclass but implemented in subclass: accessing subclass attributes?

这是我的 class 结构:

class Parent {
    public:
        void foo(); // foo() defined in superclass
};

class Child : public Parent {
    private:
        int bar;
    public:
        Child(int);
        int getBar();
};

Child::Child(int b) {
    bar = b;
}

void Child::foo() { // foo() implemented in subclass
    std::cout << getBar() << std::endl;
}

g++ 给我一个 foo() 不在 Child 范围内的错误,并将其更改为 void Parent::foo(),我得到一个错误 getBar() 是不在 Parent 范围内。

我知道虚函数,但我不想在 Child 中定义 foo(),只实现它。

如何在 Parent 方法 foo()Child 中获得方法可见性?

我的思路是class Child : public Parent这行意思是Child继承了Parent的成员方法,所以Child应该可以看到foo().

您需要在 Child class 的 public 部分编写一个原型 void foo(); 并告诉您正在使用继承的方法。然后你就可以像你一样实现了。

您无法访问 getBar(),因为您尚未声明它。声明它,它将正常工作。

您使用了错误的 C++ 术语:您所说的 "definition" 正确地称为 "declaration",而您所说的 "implementation" 正确地称为 "definition"。使用正确的术语以避免混淆和误解。

所以,如果你定义Child::foo,你也必须添加相应的声明。我在下面修复了它。

另请参阅 link RealPawPaw 在他关于 when/why 的评论中给出的,您应该使用 virtual

class Parent {
    public:
        /*virtual*/ void foo(); // this is declaration of Parent::foo
};

class Child : public Parent {
    private:
        int bar;
    public:
        Child(int); // this is declaration of constructor
        int getBar(); // this is declaration of Child::getBar
        void foo(); // this is declaration of Child::foo
};

// this is definition of Parent::foo
void Parent::foo() {
    std::cout << "Parent" << std::endl;
}

// this is definition of constructor
Child::Child(int b) {
    bar = b;
}

// this is definition of Child::getBar
int Child::getBar() {
    return bar;
}

// this is definition of Child::foo
void Child::foo() {
    std::cout << "Child: bar=" << getBar() << std::endl;
}