[英]How to access object methods from a ptr?
我收到一個error: 'heir' is not a member of 'Heir'
'heir' is not a member of 'Estate'
我的主要錯誤中'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;
}
變量heir
是Estate*
類型,但指向Heir
的對象。 這就是多態在 C++ 中的表達方式,當然也是合法的。
但是,如果您編寫heir->getHeirValue()
,編譯器只會“知道” heir
指向的對象至少是一個Estate
對象,並且它可能不依賴於(多態) heir
是否實際指向Heir
-是否為Estate
子類對象。
為了確保這一點,將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
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.