简体   繁体   English

类中的公共结构

[英]A public struct inside a class

I am new to C++, and let's say I have two classes: Creature and Human : 我是C ++的新手,让我说我有两个类: CreatureHuman

/* 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 : 我在main.cpp main函数中有这个:

Human foo;

My question is: how can I set foo's emotions? 我的问题是:我怎样才能设定foo的情绪? I tried this: 我试过这个:

foo->emotion.fear = 5;

But GCC gives me this compile error: 但是GCC给了我这个编译错误:

error: base operand of '->' has non-pointer type 'Human' 错误:' - >'的基本操作数有非指针类型'人'

This: 这个:

foo.emotion.fear = 5;

Gives: 得到:

error: 'struct Creature::emotion' is inaccessible 错误:'struct Creature :: emotion'无法访问
error: within this context 错误:在此上下文中
error: invalid use of 'struct Creature::emotion' 错误:无效使用'struct Creature :: emotion'

Can anyone help me? 谁能帮我? Thanks 谢谢


PS No I did not forget the #include s PS不,我没有忘记#include s

There is no variable of the type emotion . 没有类型emotion变量。 If you add a emotion emo; 如果你添加一个emotion emo; in your class definition you will be able to access foo.emo.fear as you want to. 在您的类定义中,您可以根据需要访问foo.emo.fear

 class Human : public Creature {

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

Change inheritance to public and define a struct emotion member in Creature class (ex. emo). 将继承更改为public并在Creature类(例如emo)中定义struct情感成员。

So you can instantiate objects of Human class (ex. foo) and atrib values to its members like 因此,您可以实例化Human类的对象(例如foo)并将值分配给其成员

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. Creature::emotion是一种类型,而不是变量。 You're doing the equivalent of foo->int = 5; 你做的相当于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'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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