![](/img/trans.png)
[英]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.