[英]How do I call method using interface pointer which is part of its concrete class and not part of interface
[英]How do I access member functions of concrete class when I'm using Polymorphism and inheritance to declare it as a pointer to the concrete class
假設我有一個抽象的 class。
class shape{
public:
shape();
double getWidth();
private:
float m_center;
};
我有一個繼承自形狀的 class 。
class triangle : public shape{
public:
triangle(vector<double> a, vector<double> b, vector<double> c);
vector<double> getPoints();
void setPoints();
private:
double pointA, pointB, pointC;
};
然后說我的代碼已格式化,以便在處理形狀時以形狀指針的形式獲取形狀數據。 但是有時我需要訪問三角形 class 的成員函數,但我只有形狀*
int main(){
shape* generalShape = new triangle()
std::cout << generalShape -> getWidth() << std::endl;
std::vector<double> tempVector = generalShape -> getPoints(); //<- can't do this part.
所以我不能從形狀* object 調用成員函數,所以我只是想知道是否有辦法做到這一點,或者我的代碼結構是否完全錯誤。
假設在基礎 class 中使用虛擬 function 沒有意義,您可以通過 dynamic_cast 來實現。 在基礎 class 中確實需要至少有一個虛擬 function。
triangle* newPtr = dynamic_cast<triangle*>(generalShape);
應該了解這種方法的成本和優勢(運行時多態性); 並考慮重新設計 class 是否更有效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.