首页 > 解决方案 > 在超类中定义但在子类中实现的方法:访问子类属性?

问题描述

这是我的班级结构:

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

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

如何在方法中获得方法Child可见Parentfoo()

我的思路是线路的class Child : public Parent意思是Child继承成员方法Parent,由此Child应该可以看到foo()

标签: c++classoopscopevisibility

解决方案


您使用了错误的 C++ 术语:您所说的“定义”正确地称为“声明”,而您所说的“实现”正确地称为“定义”。使用正确的术语以避免混淆和误解。

因此,如果您定义,则还Child::foo必须添加相应的声明。我在下面修复了它。

另请查看 RealPawPaw 在他的评论中给出的关于何时/为什么应该使用的链接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;
}

推荐阅读