Kar*_*arl 2 c++ inheritance casting
假设有两个类,如此
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);
}
Run Code Online (Sandbox Code Playgroud)
我使用私有继承来阻止HouseLocator上的GoToLocation(),因为它在那里没有意义,并强迫人们使用正确的接口.
现在我的问题是,我该如何防止这种演员?
HouseLocator *phl = new HouseLocator;
Locator *pl = (Locator*)phl;
pl->GoToLocation(10, 10);
Run Code Online (Sandbox Code Playgroud)
我是否应该记录不要这样做并将其余部分留给用户,我的意思是,如果他做错了演员,那么他的问题是什么?
使用组合而不是继承:
class Locator
{
public:
bool GoToLocation(long lat, long longtd);
};
class HouseLocator
{
Locator locator_;
public:
// internally uses locator_.GoToLocation()
bool GoToAddress(char *p);
};
Run Code Online (Sandbox Code Playgroud)
如果由于某种原因这是不实际的,那么使用private继承就是你最好的选择 - 如果用户投了HouseLocator*一个Locator* 他们正在调用未定义的行为,那就是他们的问题,而不是你的问题.