【发布时间】:2020-09-02 01:09:55
【问题描述】:
在我看来,我的班级太大太复杂,我想减少它。考虑到我创建 InitCar 类只是为了继承它并且不会显式使用此类的对象,我可以这样使用继承吗?
重构之前。人员和许可证不是我自己的类,我无法更改它们。
class Car
{
public:
void Move();
void SpeedUp();
void SpeedDw();
//More other
private:
int speed = 0;
std::string name;
int id = 0;
People owner; // not my own class
License license; // not my own class
void InitCarFromConfig()
{
//Here I read the data from the file
}
void InitOwner()
{
//Here I init the People owner
}
void InitInspection()3
{
//Here I init the License license
}
};
重构后
class InitCar
{
protected:
std::string name;
int id = 0;
People owner; // not my own class
License license; // not my own class
void InitCarFromConfig()
{
//Here I read the data from the file
}
void InitOwner()
{
//Here I init the People owner
}
void InitInspection()
{
//Here I init the License license
}
};
class Car : InitCar
{
public:
void Move()
{
InitOwner();
}
void SpeedUp();
void SpeedDw();
//More other
private:
int speed = 0;
};
这种继承使用是否可以接受,是否可能存在性能问题?
【问题讨论】:
标签: c++ inheritance design-patterns