【问题标题】:I would like to call a method declared from the parent class to the child class in C++我想在 C++ 中调用从父类声明到子类的方法
【发布时间】:2020-12-10 07:09:41
【问题描述】:

我正在尝试通过使用继承来实现从父类派生的子类,但我不断收到此错误:

/tmp/ccThP1Yc.o: In function `Cat::Cat(double, int)':
Animal.cpp:(.text+0x11a): undefined reference to `vtable for Cat'
collect2: error: ld returned 1 exit status

我正在使用 Cat::Cat(double weight, int age):Animal(name) 行的继承 'name' 是 Animal 的构造函数,我想将它重新用于 Cat,也将 Animal 中的其他方法用于 Cat。

这是我的头文件:

    #include <iostream>
    #include <string>
    #ifndef ANIMAL_H
    #define ANIMAL_H
    
    class Animal
    {
      
      public:
      
        Animal(std::string name);
        std::string get_name();
        virtual double get_weight();
        virtual int get_age();
        
      protected:
        
        std::string animalName;
        
    };
    
    class Cat: public Animal
    {
      
      public:
      
        Cat(double weight, int age);
        
        std::string get_name();
        int get_age();
        double get_weight();
        
      protected:
        
        std::string catType; //type of cat (i.e. Tabby, Siamese)
        
    };
    
    #endif

这是我的 cpp 文件:

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

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

string Animal::get_name()
{
  
  return animalName;
    
};

double Animal::get_weight()
{
    return 0.0;   
};


int Animal::get_age()
{
    return 0;
}

Cat::Cat(double weight, int age):Animal("Cat")       ////error is here
{
    
};

如果有任何帮助,我将不胜感激!谢谢!

【问题讨论】:

  • 完全不相关:在标题中,将包含放在 include guard
  • 也完全不相关:函数不需要;s

标签: c++ string class


【解决方案1】:

你在派生类中声明了虚函数

class Cat: public Animal
{
  
  public:
  
    Cat(double weight, int age);
    
    std::string get_name();
    int get_age();
    double get_weight();
    //..

但忘了定义它们。

派生类中的虚函数声明与基类中的虚函数具有相同的签名,这意味着您必须在派生类中覆盖其基类定义。

注意,在 Animal 类中,函数应该像这样声明

    virtual double get_weight() const ;
    virtual int get_age() const;

在 Cat 类中,如果你要覆盖它们,它们应该被声明为

    double get_weight() const override;
    int get_age() const override;

请记住,如果您希望类 Animal 是一个抽象类,您可以像纯虚拟一样声明虚函数

    virtual double get_weight() const = 0;
    virtual int get_age() const = 0;

这不会阻止在 Animal 类中定义它们,尽管您可以不定义它们。

注意:在这种情况下删除函数定义后的空语句

double Animal::get_weight()
{
    return 0.0;   
};
^^^

【讨论】:

  • 替代方案:如果您希望 Animal 成为 abstract base class,请将函数设为纯虚函数。例如:virtual double get_weight() = 0;
  • @user4581301 她在 Animal 类中定义了函数。:)
  • 没有太多意义。 Animal 在这些函数中返回没有任何用处。我坚持让它们成为纯虚拟的。
猜你喜欢
  • 2016-02-14
  • 1970-01-01
  • 1970-01-01
  • 2015-07-10
  • 2012-01-21
  • 2020-01-14
  • 1970-01-01
  • 2017-11-09
  • 2012-02-22
相关资源
最近更新 更多