user2252786
user2252786

Reputation: 1635

Structures as attributes

These are the attributes of my class:

    class Addition_Struct: public Addition {
    // attributes
    struct a {
        int element;
        struct a *next;
    };
    struct b {
        int element;
        struct b *next;
    };
    struct outcome {
        int element;
        struct outcome *next;
    };
    struct a a_data;
    struct b b_data;
    struct outcome outcome_data;
// methods
a convertToStackA(int); // everything is right with this line

How can I call them from inside the .cpp file? Using this->a syntax returns "type name is not allowed". Using a* as method's return value displays "Identifier is not allowed", and "Declaration is incompatible with...".

.cpp file:

a* Addition_Struct::convertToStackA(int number)
{
   // identifier "a" is undefined, and declaration is incompatible
}

Upvotes: 0

Views: 206

Answers (3)

This:

class Addition_Struct: public Addition {
// attributes
    typedef struct a {
        int element;
        struct a *next;
    } a;
};

Only defines a type named Addition_Struct::a. There is no member a for you to access with this-a. Remove the typedef to get the member you want.

EDIT

The method definition you provided is not inline (it's outside the class definition). Therefore, you must use a fully scoped type name for the return type.

Addition_Struct::a* Addition_Struct::convertToStackA(int number)
{

}

since the compiler sees the type Addition_Struct::a but not the type a.

Upvotes: 2

stijn
stijn

Reputation: 35901

From within the class you can just use a. From outside the class use the fully qualified name Addition_Struct::a.

Btw since this is C++ you can just use

struct a {
    int element;
    a *next;
};

without the typedef.

Upvotes: 1

alexrider
alexrider

Reputation: 4463

In you example you only declared structures, so your Addition_Struct have 3 structures defined, but no data members. You need to add something like

a a_data;
b b_data;
outcome outcome_data;

after structure declarations, to be able access data members like:

this->a_data;
this->b_data;
this->outcome_data;

Upvotes: 0

Related Questions