【发布时间】:2020-04-10 13:24:27
【问题描述】:
我有一个名为 associate 和 report 的两个类,分别在 associate.h 文件和 report.h 文件中声明。报表类继承report.h中的关联类如下
associate.h
class associate {
public:
int num1, num2;
}
报告.h
class report : public associate {
public:
int add();
}
我有一个 main.cpp,其中包含了 associate.h 标头并创建了对象和初始化值,如下所示。
associate a{};
a.num1 = 10;
a.num2 = 20;
现在我还有一个名为 report.cpp 的 cpp 文件,其中包含 report.h 和 associate.h 并尝试访问 num1 和 num2 值,例如
report r{};
cout << r.num1 << num2 << endl;
实际上并没有打印我在 main.cpp 中设置的 10 和 20。在这种情况下,如何从 report.cpp 访问另一个 cpp 文件中的这些值?
【问题讨论】:
-
a具有num1和num2的值,但r是一个新实例,其中这些成员尚未初始化。 -
@wally 请不要在 cmets 中回答;谢谢
-
只是添加到其他人写的内容:这个问题不是特定于继承。如果您在两个 cpp 文件中都使用了
associate,您会遇到同样的问题 - 您正在创建单独的实例,您对其中一个实例的操作不会影响另一个实例。在深入了解继承之前,您需要更好地理解更基本的 OOP 概念。 -
这样使用:
report* r = (report*)&a; cout << r->num1 << r->num2 << endl; -
@seccpur 不,不要使用裸指针。并且不要将答案放在 cmets 中。
标签: c++ class inheritance