简体   繁体   中英

Attribute declared in default? (State design pattern)

I have class Prince and Frog (both are children of State (which is virtual) and have slightly differently declared methods welcome() and sayGoodbye()

My only question is why isn't State* m_state public? (Is it default? -- and what does THAT mean?) Code is 100% good, but I have never seen declaration like this until the teacher gave us materials about Design Patterns.

Monster.h

class Monster{
    State* m_state;
public:
    Monster();
    void kiss();
    void welcome();
    void sayGoodbye();
    ~Monster();
};

Monster.cpp

Monster::Monster(){
    m_state = new Frog();
}

void Monster::kiss(){
    delete m_state;
    m_state = new Prince();
}

void Monster::welcome(){
    m_state->welcome();
}

void Monster::sayGoodbye(){
    m_state->sayGoodbye();
}

Monster::~Monster(){
    delete m_state;
}

in c++ structs are public by default and class and private by default therefore m_state is private (objects defined in class are private except if another protection statement has been made)

class Monster{
    State* m_state;
public:
    Monster();
    void kiss();
    void welcome();
    void sayGoodbye();
    ~Monster();
};

is the same as

class Monster{
private:
    State* m_state;
public:
    Monster();
    void kiss();
    void welcome();
    void sayGoodbye();
    ~Monster();
};

whereas

 struct Monster{
        State* m_state;
    public:
        Monster();
        void kiss();
        void welcome();
        void sayGoodbye();
        ~Monster();
    };

in this struct m_state is public

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