C++: Accessing parent methods and variables

前端 未结 3 550
孤独总比滥情好
孤独总比滥情好 2021-01-04 10:06

In which way should I access this parent method and parent variable?

class Base
{
public:
    std::string mWords;
    Base() { mWords = \"blahblahblah\" }
};         


        
3条回答
  •  我在风中等你
    2021-01-04 10:26

    I think this is the most common approach:

    Write(mWords);
    

    unless you run into ambiguity.

    If there's ambiguity or shadowing because you want something in a (particular) base class but something in another base class (or this class) hides it, then use the Base::name syntax.

    If a local variable is shadowing one of your members, then use this->, though in general you should try to avoid this situation. (ie: try to avoid naming locals such that they shadow members)

    I suppose one way to look at it would be to use the first of these that works and does what you want:

    1. name
    2. this->name
    3. Base::name

提交回复
热议问题