我创建了一个简单的示例(因为我的类相当大)。我已经成功地使用以下代码重现了确切的问题:
Shape.h
struct A {
int Aa = 1;
int Ab;
int Ac;
};
struct B {
int Ba = 10;
int Bb;
int Bc;
};
class Shape {
public:
virtual int type() = 0;
virtual int bonus() = 0;
A aStruct;
B bStruct;
};
这是抽象类。我故意保持简单。
Circle.h
#include "Shape.h"
class Circle : public Shape {
private: //for some reason, names of variables MUST differ from the name of the function
int type1 = 0;
int bonus1 = 1000;
public:
Circle() {}
Circle(int);
int type() { return type1; }
int bonus() { return bonus1; }
A aStruct;
B bStruct;
};
Circle.cpp
#include "Circle.h"
Circle::Circle(int s) {
type1 = s;
aStruct.Ab = 666;
aStruct.Ac = 777;
bStruct.Bb = 888;
bStruct.Bc = 999;
}
这一切都愉快地编译在一起。请原谅荒谬的值(value)观/逻辑,它们就是这样 - 荒谬。
这是主要的:
#include <iostream>
#include "Circle.h"
using namespace std;
void abstractFuncCheck(Shape& s) {
cout << s.aStruct.Ab; //does not work
}
int main() {
Circle c = 140;
//cout << c.aStruct.Ab; //works
abstractFuncCheck(c);
std::cin.get();
}
现在,问题/议题:
使用 Circle
对象,我可以检查 c
的 aStruct
和 bStruct
,它的所有值都在放置(默认 [Aa
& Ba
--> 在 Shape.h 中定义,以及在 Circle 构造函数中定义的)。
但是,如果我使用 abstractFuncCheck(Shape&)
函数来检查值,只有默认值(定义在 Shape.h --> Aa
和 Ba
) 被定义。本应在 Circle 构造函数中定义的那些显示为未定义。这意味着当我将 Circle
传递给 abstractFuncCheck(Shape&)
函数时,它表现为 Shape
,而不是 Circle
。
任何人都可以阐明这种行为吗?或者可能给我一个阅读领域来研究?
非常感谢。
最佳答案
Circle
类继承了 Shape
祖先类的 aStruct
和 bStruct
成员,然后声明了自己的aStruct
和 bStruct
成员在此之上。因此 Circle
有 2 个 aStruct
成员和 2 个 bStruct
成员。 Circle
构造函数仅初始化 Circle
成员,Shape
成员默认初始化。当您随后将 Circle
实例传递给 abstractFuncCheck()
时,它知道如何只访问 Shape
成员,您尚未使用您的Circle
值。
您需要删除重复的 Circle
成员,并让您的 Circle
方法在需要时访问继承的 Shape
成员。
class Circle : public Shape {
private: //for some reason, names of variables MUST differ from the name of the function
int type1 = 0;
int bonus1 = 1000;
public:
Circle() {}
Circle(int);
int type() { return type1; }
int bonus() { return bonus1; }
//A aStruct; <-- remove this
//B bStruct; <-- remove this
};
关于c++ - 为什么我在抽象类中使用结构时遇到问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24111725/