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

时间:2014-06-08 22:55:11

标签: 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;
}

这一切都快乐地汇集在一起​​。请原谅荒谬的价值观/逻辑,他们只是那个 - 荒谬的。

这是主要的:

#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 aStructbStruct,并检查其所有值(默认值为{{{1} }&amp; Aa - &gt;在 Shape.h ]中定义,以及Circle构造函数中定义的那些。)

但是,如果我使用Ba函数检查值,则只使用默认值(在 Shape.h - &gt; abstractFuncCheck(Shape&)和{{1中定义}})已定义。应该在Circle构造函数中定义的那些显示为未定义。这意味着当我将Aa传递给Ba函数时,它的行为与Circle相同,而不是abstractFuncCheck(Shape&)

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

非常感谢。

1 个答案:

答案 0 :(得分:2)

您的Circle班级会继承aStruct祖先班级中的bStructShape成员,然后声明自己的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
};