C ++调用超类

时间:2012-02-28 11:09:08

标签: c++ inheritance

我主要是Java和AS3程序员,但是现在我正在用C ++工作,我偶然发现了一个问题。 我有一个基类(我们称之为ClassA),它有一个私有变量var1。在这个类中,我有一个方法getVar1(),它返回一个指向该变量的指针。

接下来我有另一个扩展Base的类(我们称之为ClassB)。如何从超类中调用getVar1()? 在java中,它就像this.var1 = super.getVar1()。

一样简单

我读到它就像var1 = ClassA :: getVar1(),但我不确定这是否适合使用变量(也就是指针可以改变)。

感谢。

3 个答案:

答案 0 :(得分:6)

可以称之为ClassA :: getVar1()。

但是,如果你想要java方式,你可以使方法“虚拟”。这意味着无论何时编写getVar1(),它都不依赖于您在其前面编写的类型(因此在编译时),但它取决于调用它时对象的类型(在运行时)。因此,c ++保留了一个内部v表来查找适当的方法。它等同于java方式,称为后期绑定。

答案 1 :(得分:3)

getVar1()应该足够了

class ClassB : public ClassA
{
...
   void foo() { yourvartype* v = getVar1(); ... }
};

如果OTOH在getVar1()中定义了另一个ClassB,则应使用ClassA::getVar1()来帮助编译器识别要调用的函数。

答案 2 :(得分:2)

以下是一个显示发生情况的小例子: - 初始化x为10 - B在20处初始化x 在下面你可以看到虚函数调用是如何工作的以及如何调用你的父项(即使你以不同方式初始化值)

要记住的最重要的事情是,即使你调用你的超级函数(A :: GetX),它仍然使用你自己的类中的值(B :: x)

class A
{
public:
    A::A() : x(10) {}
virtual int GetX() {return x*2;}
protected:
    int x; 
};

class B : public A
{
public:
    B::B() : A()
    {
        x = 20;
    }
    virtual int GetX() {return x;}
};

int _tmain(int argc, _TCHAR* argv[])
{
    A* a1 = new A();
    B* b1 = new B();
    int test1 = a1->GetX(); // returns 20 (because x is 10, but function doubles value)
    int test2 = b1->GetX(); // returns 20 (because x is initialized at 20)
    return 0;
}

现在,如果我们将B :: GetX更改为:

virtual int GetX() {return A::GetX();}

我们得到以下结果:

int _tmain(int argc, _TCHAR* argv[])
{
A* a1 = new A();
B* b1 = new B();
int test1 = a1->GetX(); //returns 20 (as previously)
int test2 = b1->GetX(); // return 40 (x is initialized by B at 20, but then the
                        // A:GetX is called, which doubles the result)
return 0;
}