我创建了一个简单的例子(因为我的课程相当大)。我已设法使用以下代码重现确切的问题:
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;
}
这一切都快乐地汇集在一起。请原谅荒谬的价值观/逻辑,他们只是那个 - 荒谬的。
这是主要的:
#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
,并检查其所有值(默认值为{{{1} }&amp; Aa
- &gt;在 Shape.h ]中定义,以及Circle构造函数中定义的那些。)
但是,如果我使用Ba
函数检查值,则只使用默认值(在 Shape.h - &gt; abstractFuncCheck(Shape&)
和{{1中定义}})已定义。应该在Circle构造函数中定义的那些显示为未定义。这意味着当我将Aa
传递给Ba
函数时,它的行为与Circle
相同,而不是abstractFuncCheck(Shape&)
。
有人可以对这种行为有所了解吗?或者可能给我一个阅读领域来研究?
非常感谢。
答案 0 :(得分:2)
您的Circle
班级会继承aStruct
祖先班级中的bStruct
和Shape
成员,然后声明自己的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
};