为什么我在抽象类中使用结构时遇到问题
Why am I having issues using a struct in an abstract class?
我创建了一个简单的例子(因为我的类相当大(。我已经设法使用以下代码重现了确切的问题:
形状.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;
};
这是抽象类。我故意保持简单。
圆圈
#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;
};
圈子.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
,并且它的所有值都已到位(默认的值 [ 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()
时,它知道如何仅访问尚未使用Circle
值初始化的Shape
成员。
您需要删除重复的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# 中序列化这些值以在C++中作为已知结构正确读取时遇到问题
- 使用向量和结构在C 中遇到错误
- 在结构成员的打印价值时遇到困难
- 我必须将记录结构转换为一类,并且不断遇到多个错误
- 在使用结构体和用函数填充其变量(使用指针)时遇到问题
- 我在动态分配结构时遇到问题
- 在将结构插入设置C++时遇到问题
- 迭代结构时遇到问题
- 在二维结构数组C++遇到问题
- 谁让狗出去的?- 当"Is-A"在类层次结构中遇到"Has-A"时销毁对象
- 从流或字节中读取结构时遇到问题
- 在将 void 指针转换为结构时获取值时遇到问题
- 将元素添加到遇到的结构数组C++"error no match for ‘operator=’"
- 在将整个结构数组传递给函数时遇到问题
- 在使用数据结构从文件中读取数据时遇到麻烦
- 读取int*类型的结构属性值时遇到问题
- 为什么我在抽象类中使用结构时遇到问题
- 从文本文件中读取已创建的结构类型时遇到问题