c++ - C2084 - 函数已经有主体

标签 c++ virtual

我遇到错误“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/

相关文章:

c++ - 参数列表中的可选 "name"?

c++ - 识别 boost::shared_ptr<boost::thread> 中的对象

C++:私有(private)虚函数与纯虚函数

c++ - 如何在没有多态效果的情况下调用虚方法?

c++ - 关于 operator new 重载和异常的问题

c++ - 对 C++ 异常处理很困惑

c++ - 虚方法和构造函数?

c++ - 基本的 C++ 继承

c# - 反射说接口(interface)方法在实现类型中是虚拟的,而实际上它们不是?

C++11 删除类类型?