【发布时间】:2011-04-15 08:39:58
【问题描述】:
假设有两个这样的类
class Locator
{
public:
// this goes to the specified latitide and longitude
bool GoToLocation(long lat, long longtd);
};
class HouseLocator : private Locator
{
public:
// this internally uses GoToLocation() after fetching the location from address map
bool GoToAddress(char *p);
}
我使用私有继承来阻止 HouseLocator 上的 GoToLocation(),因为它在那里没有意义,并迫使人们使用正确的接口。
现在我的问题是,我怎样才能防止这种类型的转换?
HouseLocator *phl = new HouseLocator;
Locator *pl = (Locator*)phl;
pl->GoToLocation(10, 10);
我是否应该只记录不这样做并将其余的留给用户,我的意思是,如果他做出错误的演员表,那是他的问题吗?
【问题讨论】:
-
你无法阻止它。如果您不希望它工作,并且没有意义,为什么不让 HouseLocator 包含定位器,而不是从它继承?
-
无论您做什么,人们都可以使用例如:特定于平台的技巧。像你一样使用私有继承就足够了 - 你清楚地表明不应该使用
Locator接口,如果用户想要破坏东西,那不是你的问题。 -
查看stackoverflow.com/questions/5650790/… 的答案,了解一些可以帮助您的 GCC 选项。
-
丑陋的解决方案编号 XXX... 更改基类,使 GoToLocation 是虚拟的,并在 HouseLocator 中覆盖它以抛出 NotSupportedException...。
-
@forsvarir : 呃.. 编译时问题的运行时错误?到那时,为什么首先要使用静态类型语言?
标签: c++ inheritance casting