为什么我在抽象类中使用结构时遇到问题

Why am I having issues using a struct in an abstract class?

本文关键字:结构 遇到 问题 抽象类 为什么      更新时间:2023-10-16

我创建了一个简单的例子(因为我的类相当大(。我已经设法使用以下代码重现了确切的问题:

形状.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 对象,我可以检查 caStructbStruct,并且它的所有值都已到位(默认的值 [ Aa & Ba --> 在 Shape.h 中定义],以及 Circle 构造函数中定义的值(。

但是,如果我使用 abstractFuncCheck(Shape&) 函数检查值,则仅定义默认值(在 Shape.h --> AaBa 中定义(。应该在 Circle 构造函数中定义的那些显示为未定义。这意味着当我将Circle传递给 abstractFuncCheck(Shape&) 函数时,它的行为是 Shape ,而不是Circle

谁能对这种行为有所了解?或者可以给我一个阅读领域来研究?

谢谢。

您的Circle类从Shape祖先类继承aStructbStruct成员,然后在此基础上声明自己的aStructbStruct成员。 因此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
};