C++ 如何在c++;
我有一个关于继承变量的问题。我的部分源代码:C++ 如何在c++;,c++,inherited,C++,Inherited,我有一个关于继承变量的问题。我的部分源代码: class Piston{ //abstract class ... //virtual functions }; class RectangularPiston: public Piston { ... //non virtual implementation of the Piston functions bo
class Piston{ //abstract class
... //virtual functions
};
class RectangularPiston: public Piston
{
... //non virtual implementation of the Piston functions
bool setGridSize(...) //this function doesn't exists in the Piston class
{
...
}
}
class Transducer{ //abstract class
... //virtual functions
protected:
Piston *m_piston;
};
class RectilinearTransducer: public Transducer
{
... //non virtual implementation of the Piston functions
bool setGridSizeOfPiston(...)
{
return m_piston->setGridSize(...); //doesn't work
}
}
直线传感器装有一个m_活塞,它始终是一个直线活塞!
但是m_活塞是由Transformer类继承的,我不能使用setGridSize()函数
错误消息:错误C2039:“setGridSize”:不是“活塞”的元素
活塞类中不存在函数setGridSize
我怎样才能解决这个问题?
我是否应该像使用虚拟函数一样覆盖m_活塞变量?m_活塞变量作为活塞*m_活塞存在,因为我通过Transformer类继承了它
感谢您的帮助您需要将
setGridSize
设置为活塞的虚拟功能(纯虚拟或其他)
e、 g
如果无法在父级中将
setGridSize
设置为虚拟函数,则可能需要添加一个函数,该函数只将m_活塞
强制转换为RectangularPistone*
,然后在类需要引用m_活塞
时调用此函数
RectangularPiston* getRecPiston() {
return static_cast<RectangularPiston*>(m_piston);
}
bool setGridSizeOfPiston(...) {
return getRecPiston()->setGridSize(...)
}
rectangular活塞*getrec活塞(){
返回静态_铸件(m_活塞);
}
bool setGridSizeOfPiston(…){
返回getRec活塞()->setGridSize(…)
}
错误消息是什么?setGridSize()是公共的吗?错误C2039:“setGridSize”:不是“活塞”的元素。请更新有问题的错误消息是活塞中的虚拟函数之一
?如果m_活塞
始终是一个RectlinearPiston
,则将其声明为一个,而不是活塞
动态_强制转换
如果无法执行强制转换,则返回NULL。如果您知道m_活塞
始终是一个rectangular活塞
,请使用static_cast
。
RectangularPiston* getRecPiston() {
return static_cast<RectangularPiston*>(m_piston);
}
bool setGridSizeOfPiston(...) {
return getRecPiston()->setGridSize(...)
}