如何在c ++中访问基类的成员变量?

时间:2014-03-01 02:30:18

标签: c++ visual-c++

我正在尝试访问基类的成员变量.. 怎么做?

=====================以下是ClassA(父类)=================== ======

class ClassA 
{
public:
    int member_Var; // Parent member_var

    ClassA();
    ~ClassA();
    void ClassA::initProcess();
};

ClassA::ClassA(){}
ClassA::~ClassA(){}

void ClassA::initProcess()
{
   member_Var = 20;
}

=================以下是ClassA的子类ClassB ================

class ClassB : public ClassA
{
public:
    int member_Var; // Subclass member_var

    ClassB();
    ~ClassB();

    void ClassB::initProcess();
};

ClassB::ClassB(){}
ClassB::~ClassB(){}

void ClassB::initProcess()
{
   ClassA->member_Var = 10; // Is this correct? or How to access base instances's member variable?
   member_var = 100;
}

1 个答案:

答案 0 :(得分:4)

您需要指定ClassA::member_Var以明确引用基类中的那个。

void ClassB::initProcess()
{
   ClassA::member_Var = 10;
   member_var = 100;
}