c++ - 在超类中定义但在子类中实现的方法:访问子类属性?
问题描述
这是我的班级结构:
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
可见Parent
性foo()
?
我的思路是线路的class Child : public Parent
意思是Child
继承成员方法Parent
,由此Child
应该可以看到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;
}
推荐阅读
- gem5 - 如何在 gem5 中设置 cortex a76?
- r - 手动或使用 R 计算 p 值
- react-data-grid - React-data-grid 有处理分页的机制吗?
- java - Hive:无法插入到带有地图列的表中
- scala - 将具有 Pig Map 类型的列的数据导入 spark Dataframe?
- vue.js - 在 vue.js 中悬停时覆盖
- php - 如何通过ajax返回一个数组
- javascript - 无法在 testcafe 中切换全屏
- php - 如何使用 PHP 和 XML 示例创建 SOAP 请求?
- django - 即使重新安装后 Django 也完全崩溃了