C2084 - 函数已经有主体

C2084 - function already has a body

我 运行 遇到错误 "C2084 - function 'void Pet::display(void)' already has a body"。 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_

Dog.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 

Dog.cpp

#include "Dog.h"
#include "Pet.h"
#include <iostream>

void Pet::display() {
    cout << "Name: " << name << endl;
    cout << "Breed: " << breed << endl;
    cout << "Type: Dog" << endl;
}

您在派生自另一个 class Pet 的 class Dog 中声明方法 display 纯虚拟。但是 Pet class 已经有一个具体的方法叫做 display。这就是您收到此错误的原因。

Petclass中声明display为纯虚函数,然后在其子classDog.[=18=中给出具体实现]

Pet.h 中,您已经为 display() 定义了一个正文,它什么都不做。

Pet.h:

class Pet {
    /* other class members */
    virtual void display() {}; // Here is your virtual function with an empty body.
};

Dog.h:

class Dog : public Pet {
    /* other class members */
    virtual void display() = 0; // This pure virtual function which is inheriting from Pet which is not purely virtual.

};

交换两者。

  • 制作Petvirtual void display() = 0,即纯虚函数。
  • 创建 Petvirtual void display(),即您已经在 Dog.cpp 中实现的虚函数。

解法:

Pet.h:

class Pet {
    /* other class members */
    virtual void display() = 0; // Make this a pure virtual function. It does not have an implementation.
};

Dog.h:

class Dog : public Pet {
    /* other class members */
    virtual void display(); // This virtual function is implemented in Dog.cpp.

};

您似乎想定义 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"文件中函数原型后有“=0”,这意味着你不应该直接实例化宠物class(抽象class)。