【问题标题】:How to access object methods from a ptr?如何从 ptr 访问对象方法?
【发布时间】:2017-10-27 21:49:23
【问题描述】:

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

下面是代码:

#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;
}

【问题讨论】:

  • 您正在通过Estate* 呼叫getHeirValueEstate 类没有该名称的功能。正确的答案取决于当有人这样做时您希望发生什么——我们不知道。 (你的意思是Heir *heir?)
  • 也许我对继承感到困惑。是否可以使用我当前的代码调用继承人getHeirValue() 中的方法,并使用我的对象Estate heir = new Heir(2000,3000) 调用方法getEstateValue
  • 由于heirEstate* 类型,它可以指向Estate 类型的对象。但随后你调用了一个函数,getEstateValue,在它上面调用 Estate 类型的对象是不合法的。那么在这种情况下你希望发生什么?如果您的答案是这种情况在代码中是不可能的,请将 heir 更改为 Heir* 而不是 Estate* 类型,以明确它必须指向 Heir而不是Estate。但只要你想让它成为可能,你就必须以某种方式实现它。

标签: c++ pointers inheritance


【解决方案1】:

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

然而,如果你写heir-&gt;getHeirValue(),编译器只是“知道”heir指向的对象至少是一个Estate-object,它可能不依赖于是否(多态)heir实际上是否指向EstateHeir-subclass 对象。

为确保这一点,请将 heir 的值转换为 Heir 的实例,以便“告诉”编译器它可能依赖于 heir 指向此类对象的事实:

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

顺便说一句:对于getEstateValue,不需要这样的转换,因为heir的类型是Estate*,这样heir指向的对象至少是一个Estate对象,因此总是提供getEstateValue

【讨论】:

  • 谢谢! cout &lt;&lt; "Heir value is: " &lt;&lt; static_cast&lt;Heir*&gt;(heir)-&gt;getHeirValue() &lt;&lt; endl; 解决了我的问题。
  • 不客气。如果它对您有帮助,请不要犹豫接受答案:-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多