使用此代码:
class Plant
{
public:
virtual std::string getPlantName();
virtual void setPlantName(std::string s);
virtual std::string getPlantType();
virtual void setPlantType(std::string s);
};
class Carrot : public Plant
{
public:
Carrot();
~Carrot();
private:
std::string _plantName;
};
接着:
#include "Carrot.hpp"
Carrot::Carrot()
{
}
Carrot::~Carrot() { }
std::string Carrot::getPlantName() { return _plantName; }
我收到一个链接错误:
Carrot.cpp:16:21: Out-of-line definition of 'getPlantName' does not match any declaration in 'Carrot'
所以这里的目标是创建一个 Plant 类,其他类可以像这样扩展class Carrot : public Plant
但是,我不确定的是我是否可以只inline使用其中的功能,Plant这样我就不必在每个类中创建这些get和set功能,如 Carrot 或 Peas 等?
如果我这样做了:
inline virtual std::string getPlantName( return _plantName; );
那行得通吗?然后我会添加std::string _PlantName;,class Plant然后当我从中创建时Carrot,Plant我会得到所有相同的函数,并且Carrot会有像_plantName等这样的变量,对吗?
所以这将是:
class Plant
{
public:
inline virtual std::string getPlantName( return _plantName; );
virtual void setPlantName(std::string s);
virtual std::string getPlantType();
virtual void setPlantType(std::string s);
private:
std::string _plantName;
};
class Carrot : public Plant
{
public:
Carrot();
~Carrot();
};
#include "Carrot.hpp"
Carrot::Carrot()
{
setPlantName(CARROT::plantName);
}
Carrot::~Carrot() { }