我遇到错误“C2084 - 函数‘void Pet::display(void)’已经有主体”。 Dog.cpp 文件发生错误。对这个问题有点困惑。任何帮助,将不胜感激。
Pet.h
#ifndef _PET_H_
#define _PET_H_
#include <string>
using namespace std;
enum Type { dog = 0, cat };
class Pet {
private:
string name, breed; // private local variables
Type type;
public:
Pet(string pet_name, string pet_breed, Type pet_type); // constructor
// accessor methods
string getName();
string getBreed();
Type getType();
virtual void display() {};
};
#endif // _PET_H_
狗.h
#ifndef _DOG_H_
#define _DOG_H_
#include "Pet.h"
#include <string>
using namespace std;
class Dog : public Pet {
public:
Dog(string pet_name, string pet_breed, Type pet_type) : Pet(pet_name, pet_breed, pet_type) {
} // constructor
virtual void display() = 0;
};
#endif
狗.cpp
#include "Dog.h"
#include "Pet.h"
#include <iostream>
void Pet::display() {
cout << "Name: " << name << endl;
cout << "Breed: " << breed << endl;
cout << "Type: Dog" << endl;
}
最佳答案
您似乎想定义 Dog::display 而忘记将 Pet 重命名为 Dog:
void Dog::display() {
cout << "Name: " << name << endl;
cout << "Breed: " << breed << endl;
cout << "Type: Dog" << endl;
}
同时从以下位置删除“= 0”:
virtual void display() = 0;
在“Dog.h”中。
在“Pet.h”文件中函数原型(prototype)后有“= 0”,这意味着你不应该直接实例化 Pet 类(抽象类)。
关于c++ - C2084 - 函数已经有主体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43175572/