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

标签 c++ struct abstract-class

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

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

但是,如果我使用 abstractFuncCheck(Shape&) 函数来检查值,只有默认值(定义在 Shape.h --> Aa Ba) 被定义。本应在 Circle 构造函数中定义的那些显示为未定义。这意味着当我将 Circle 传递给 abstractFuncCheck(Shape&) 函数时,它表现为 Shape,而不是 Circle

任何人都可以阐明这种行为吗?或者可能给我一个阅读领域来研究?

非常感谢。

最佳答案

Circle 类继承了 Shape 祖先类的 aStructbStruct 成员,然后声明了自己的aStructbStruct 成员在此之上。因此 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/

相关文章:

c++ - Sscanf() 函数

c++ - 如果在其库未直接包含在源代码中时使用标识符,是否可以强制 Visual Studio 抛出错误?

c - 使用指针和非指针变量释放结构体

struct - Rust 结构无法替换 HashMap 中的特征

java - 什么时候使用抽象类?一个接口(interface)?

java - 有一个扩展抽象类的空子类可以吗?

C++:如何从另一个抽象类的派生类中获取抽象派生类方法的不同行为?

c++ - 是否可以使用不在 header 中的 C++ 库代码?

c++ - 如何实现一个公开多个范围的容器?

c - 如何释放另一个链表中的链表?