【问题标题】:Undefined reference to a virtual function [duplicate]对虚函数的未定义引用[重复]
【发布时间】:2021-12-30 13:46:52
【问题描述】:

booking.h

#ifndef _BOOKING_H_
#define _BOOKING_H_

#include <string>

class Event {
  private:
   std::string event_option;
  public:
   Event(std::string event_option);
   virtual ~Event();
   void list_specific_event_details();
   virtual void list_details();
};

class Films : public Event {
 private:
  std::string movie_option;
 public:
  Films(std::string movie_option);
  void list_details();
};

class Live_Music : public Event {
 private:
  std::string live_music_option;
 public:
  Live_Music(std::string live_music_option);
  void list_details();
};

class Standup_Comedy : public Event {
 private:
  std::string comedy_option;
 public:
  Standup_Comedy(std::string comedy_option);
  void list_details();
};
#endif

booking.cpp

#include "booking.h"
#include <string>
Event::Event(std::string event_option)
{
  this->event_option = event_option;

}

Event::~Event()
{
}


void Event::list_specific_event_details()
{
  return list_details();
}


Films::Films(std::string movie_option) : Event("Films")
{
  this->movie_option = movie_option;

}

void Films::list_details()
{
    //some code ...

    return;

}

Live_Music::Live_Music(std::string live_music_option) : Event("Live_Music")
{
  this->live_music_option = live_music_option;

}

void Live_Music::list_details()
{

    //some code...

  return;

}

Standup_Comedy::Standup_Comedy(std::string comedy_option) : Event("Standup_Comedy")
{
  this->comedy_option = comedy_option;

}

void Standup_Comedy::list_details()
{
    //some code...
  return;

}

ma​​in.cpp

#include "booking.h"
#include <iostream>
#include <vector>
#include <string>

int main()
{
  std::vector <Event *> choice;
  choice.push_back(new Films("f"));
  choice.push_back(new Live_Music("l"));
  choice.push_back(new Standup_Comedy("s"));

  for(unsigned i = 0; i < choice.size(); i++)
    {
      choice[i] -> list_specific_event_details();
    }


  for (Event * e: choice) delete e;
  choice.clear();

}

我已经编写了上面的代码块,但在尝试编译时出错。

错误如下:

usr/lib/gcc/x86_64-pc-cygwin/11/../../../../x86_64-pc-cygwin/bin/ld: /tmp/ccuWXzBM.o:booking.cpp:(.rdata$_ZTV5Event[_ZTV5Event]+0x20): undefined reference to `Event::list_details()'
collect2: error: ld returned 1 exit status

为什么会出现此错误,我该如何解决?

【问题讨论】:

  • 给定的 dup 错误!这里我们讨论的是接口定义,而不是未定义的引用......按下按钮有点快......
  • 你的代码中Event::list_details()在哪里?
  • @Eljay:不需要...缺少的部分是=0;
  • @Klaus • 也许。不确定 Event 是否打算成为一个抽象基类,或者只是本身可以实例化的公共基类(当然,它没有在提供的代码中实例化,因此存在歧义)。
  • @Eljay:但我们可以假设:代码不需要Event 的实例,并且所有内容都源自Event,并且所有类都实现了缺少的功能,或多或少es 的意思很明显。不是吗:-)

标签: c++ virtual-functions


【解决方案1】:

你还没有定义你的方法Event::list_details()。如果你只想声明函数但不想实现它,也就是所谓的接口,你可以将其设为pure virtual method

class Event
{
...
    virtual void list_details() = 0;
...
};

【讨论】:

    猜你喜欢
    • 2012-11-06
    • 2015-12-30
    • 2012-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-30
    • 1970-01-01
    相关资源
    最近更新 更多