【发布时间】:2017-06-22 08:45:47
【问题描述】:
看到下面question,我问自己是否有更好的方法来解决这个问题,所以不需要演员表。 考虑以下代码:
#include <iostream>
class Base
{
public:
virtual ~Base() {}
};
class Derived : public Base
{
protected:
int someVar = 2;
public:
int getSomeVar () {return this->someVar;}
};
int main()
{
Base B = Base();
Derived D = Derived();
Base *PointerToDerived = &D;
Base *PointerToBase = &B;
std::cout << dynamic_cast<Derived*>(PointerToDerived)->getSomeVar() << "\n"; //this will work
std::cout << dynamic_cast<Derived*>(PointerToBase)->getSomeVar() << "\n"; //this will create a runtime error
return 0;
}
有没有更好的方法来设计这个,所以不需要强制转换并且可以避免这样的运行时错误?
【问题讨论】:
-
它不会产生运行时错误,它会表现出未定义的行为,可能导致运行时错误
-
这完全取决于你真正想要做什么......“通过基类访问派生类属性。”可能会出现在许多情况下,其中许多情况可以通过良好的设计直接避免......因此,如果没有更多关于您真正目标的信息,将很难提供好的建议......
-
取决于你想做什么,最直接的解决方案可能只是虚函数
-
@nefas:我认为你是对的。访问者模式可能是处理这个问题的理想方式。你能举个例子吗?我无法绕过它。
标签: c++ pointers base dynamic-cast derived