在删除构造函数行时,错误消失了。
Dog::Dog(std::string name, double height, double weight, std::string sound) : Animal(name, height, weight) {
this -> sound = sound;
}
void Dog::ToString() {
//std::cout << this->name << " is " << this->height << " cm's tall and " << this->weight << " kg's in weight" << std::endl;
//cannot do the line above as it is private, if it were to be protected we could call it. "sharing with childs of class"
std::cout << GetName() << " is " << GetHeight() << " cm's tall and " << GetWeight() << " kg's in weight" << std::endl;
}
class Animal {
private:
std::string name;
double height;
double weight;
static int numOfAnimals;
static bool canTalk;
public:
std::string GetName() {
return name;
}
double GetHeight() {
return height;
}
double GetWeight() {
return weight;
}
void SetName(std::string name) {
this->name = name;
}
void SetHeight(double height) {
this->height = height; //height that is passed in through parameter becomes the height
}
void SetWeight(double weight) {
this->weight = weight;
}
void SetAll(std::string, double, double);
Animal(std::string, double, double); //constructor
Animal(); //for when no parameters are passed
~Animal(); //destructor
static int GetNumOfAnimals() {
return numOfAnimals;
}
void ToString();
};
@inisheer要求的动物类的代码和构造函数
答案 0 :(得分:4)
您已经声明了构造函数:
Animal(std::string, double, double); //constructor
但是,您没有定义它,这在这里很重要。编译Dog
构造函数后,将对Animal::Animal(std::string, double, double)
进行引用,链接器将尝试对此进行引用,但无法对其进行解析。在后续的comment中,您仍然尚未定义此特定的构造函数。
您需要实际定义Animal
构造函数和析构函数,例如
Animal(std::string name, double height, double weight) : name(name), height(height), weight(weight) {}
不相关::这里有潜在的rule-of-three违规隐患,一旦开始与需要特定管理的资源进行交互,您应该更加意识到这一点。您已定义了析构函数,但未定义拷贝构造函数或拷贝赋值运算符。在您的情况下,这很好,因为dtor除了会产生打印副作用之外,没有做任何有趣的事情,但是您应该努力遵循此准则,以避免将来出现麻烦。