c++ - 在父类(super class)中定义但在子类 : accessing subclass attributes? 中实现的方法

标签 c++ class oop scope visibility

这是我的类结构:

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 code> 应该能够看到 foo()

最佳答案

你使用了错误的 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;
}

关于c++ - 在父类(super class)中定义但在子类 : accessing subclass attributes? 中实现的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58906332/

相关文章:

c++ - 创建包含多个变量的大字符串的最佳方法?

c++ - 如何制作一个实例化类并将它们排序在地址列表中的循环?

c++ - 如何判断哪个 C++ 可再发行组件包含在 InstallShield 安装程序中?

flutter - 在 Dart 中创建类的实例

Java 如何使用instanceof返回一个新的对象类型?

c++ - 将基于递归 DFS 的拓扑排序转化为非递归算法(不丢失循环检测)

java - OOP设计,在主类之外调用某些方法

php通过字符串访问类

java - 如何在此 Builder 实现中摆脱 instanceof

c++ - 如何触发数据成员的复制构造函数?