如何从ptr访问对象方法?

时间:2017-10-27 21:49:24

标签: c++ pointers inheritance

我的主要内容出现error: 'heir' is not a member of 'Heir''heir' is not a member of 'Estate'错误。我试图使用getEstateValue()getHeirValue()方法显示继承人和地产的总价值。是否可以使用Estate heir = new Heir(2000,3000)访问这两种方法。我有继承类继承自Estate类。感谢您的帮助

下面是代码:

#include <stdio.h>
#include <iostream>
#include <cmath>

using namespace std;

class Estate{
    protected:
        double estateValue;

    public:
        Estate(double estateValue){
            this->estateValue = estateValue;
        }

        virtual double totalEstateValue(){
            return estateValue;
        }

        double getEstateValue(){
            return estateValue;
        }
};

class Heir:public Estate{
    protected:
        double heirValue;

    public:
        Heir(double heirValue, double estateValue):Estate(estateValue){
            this->heirValue = heirValue;
        }

        double totalEstateValue(){
            return heirValue+=Estate::estateValue;
        }

        double getHeirValue(){
            return heirValue;
        }
};

int main(){
    Estate* heir = new Heir(2000, 3000);

    //how do i access the methods in heir class? is it heir->getHeirValue?
    //how do i access the methods in the estate class? is it heir->getEstateValue?
    //here is where I am getting the error
    cout << "Heir value is: " << Heir::heir->getHeirValue() << endl;
    cout << "Estate value is: " << Heir::heir->getEstateValue() << endl;
    //here is where I am getting the error
    cout << "Total value is: " << heir->totalEstateValue() << endl;

    delete heir;
    heir = nullptr;
    return 0;
}

1 个答案:

答案 0 :(得分:1)

变量heir的类型为Estate*,但指向Heir的对象。当然,这就是多态性在C ++和法律中的表达方式。

但是,如果你写heir->getHeirValue(),编译器就会知道&#34; heir指向的对象至少是Estate - 对象,它可能不依赖于(多态)heir是否实际指向Heir - 子类对象是Estate还是没有。

要确保这一点,请将heir的值转换为Heir的实例,以便&#34;告诉&#34;编译器可能依赖于heir指向这样一个对象的事实:

cout << "Heir value is: " << static_cast<Heir*>(heir)->getHeirValue() << endl;
cout << "Estate value is: " << heir->getEstateValue() << endl;

BTW:对于getEstateValue,不需要这样的强制转换,因为heir的类型为Estate*,因此heir指向的对象至少应为{ {1}}对象因此将始终提供Estate