这是我的类结构:
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/