首页 > 解决方案 > 我正在尝试编写一个类,其中子类将从父类继承方法,但我的代码无法编译

问题描述

我只是想让我的代码编译。我以前做过这个,它的方法看起来完全一样,但是由于某种原因,当我尝试使用不同的方法运行它时,它不会编译。错误在 cpp 文件中。任何帮助都会很棒!谢谢

错误是:

/tmp/ccexQEF7.o: In function `Animal::Animal(std::string)':
Animal.cpp:(.text+0x11): undefined reference to `vtable for Animal'
collect2: error: ld returned 1 exit status

这是我的头文件:

#include <iostream>
#ifndef ANIMAL_H
#define ANIMAL_H

class Animal
{
  
  public:
  
    Animal(std::string name);
    std::string get_name();
    virtual int get_weight();
    virtual int get_age();
    
  protected:
    
    std::string animalName;
    
};

class Cat: public Animal
{
  
  public:
  
    Cat(double weight, int age);
    
    std::string get_name();
    virtual int get_age();
    virtual int get_weight();
    
  protected:
  
    std::string catType;     
};

#endif

这是我的 cpp 文件:

#include <iostream>
#include "Animal.h"
using namespace std;

Animal::Animal(string name)
{
    animalName = name;
};

标签: c++classinheritancevirtual-functionsfunction-definition

解决方案


您必须在基类中定义虚拟成员函数get_weightget_age明确地或将它们声明为纯虚拟函数,例如

class Animal
{
  
  public:
  
    Animal(std::string name);
    std::string get_name();
    virtual int get_weight() = 0;
    virtual int get_age() = 0;
    
  protected:
    
    std::string animalName;
    
}

在派生类中,您应该使用说明符覆盖它们override,例如

    int get_weight() override;
    int get_age() override;

并提供它们的定义。

请注意,最好将成员函数声明为常量函数,例如

class Animal
{
  
  public:
  
    Animal(std::string name);
    std::string get_name();
    virtual int get_weight() const = 0;
    virtual int get_age() const = 0;
    
  protected:
    
    std::string animalName;
    
}

因为它们似乎不会更改调用它们的对象。


推荐阅读