简体   繁体   中英

A public struct inside a class

I am new to C++, and let's say I have two classes: Creature and Human :

/* creature.h */
class Creature {
private:
public:
    struct emotion {
        /* All emotions are percentages */
        char joy;
        char trust;
        char fear;
        char surprise;
        char sadness;
        char disgust;
        char anger;
        char anticipation;
        char love;
    };
};

/* human.h */
class Human : Creature {

};

And I have this in my main function in main.cpp :

Human foo;

My question is: how can I set foo's emotions? I tried this:

foo->emotion.fear = 5;

But GCC gives me this compile error:

error: base operand of '->' has non-pointer type 'Human'

This:

foo.emotion.fear = 5;

Gives:

error: 'struct Creature::emotion' is inaccessible
error: within this context
error: invalid use of 'struct Creature::emotion'

Can anyone help me? Thanks


PS No I did not forget the #include s

There is no variable of the type emotion . If you add a emotion emo; in your class definition you will be able to access foo.emo.fear as you want to.

 class Human : public Creature {

C ++默认为class es的私有继承。

Change inheritance to public and define a struct emotion member in Creature class (ex. emo).

So you can instantiate objects of Human class (ex. foo) and atrib values to its members like

foo.emo.fear = 5;

or

foo->emo.fear = 5;

Code changed:

/* creature.h */
class Creature {
private:
public:
    struct emotion {
        /* All emotions are percentages */
        char joy;
        char trust;
        char fear;
        char surprise;
        char sadness;
        char disgust;
        char anger;
        char anticipation;
        char love;
    } emo;
};

/* human.h */
class Human : public Creature {

};

Creature::emotion is a type, not a variable. You're doing the equivalent of foo->int = 5; but with your own type. Change your struct definition to this and your code will work:

struct emotion_t {  // changed type to emotion_t
        // ...
    } emotion;      // declaring member called 'emotion'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM