[英]Undefined reference to vtable for Compte
我正在嘗試為要遵循的課程構建C++
項目,但遇到了很多麻煩。
我有這個標題:
#ifndef COMPTE_H_
#define COMPTE_H_
#include <string>
class Compte {
public:
Compte (unsigned int p_noCompte, double p_tauxInteret, double p_solde,const std::string& p_description);
virtual ~Compte (){} ;
void asgSolde (const double p_solde);
unsigned int reqNoCompte () const;
double reqTauxInteret () const;
double reqSolde () const;
std::string reqDescription () const;
std::string reqCompteFormate() const;
virtual Compte* clone() const;
virtual const double calculerInteret();
private:
unsigned int m_noCompte;
double m_tauxInteret;
double m_solde;
std::string m_description;
};
#endif /* COMPTE_H_ */
和相應的cpp文件:
#include "Compte.h"
#include <string>
#include <sstream>
using namespace std;
Compte::Compte (unsigned int p_noCompte, double p_tauxInteret, double p_solde, const string& p_description)
: m_noCompte(p_noCompte), m_tauxInteret(p_tauxInteret), m_solde(p_solde), m_description(p_description)
{
}
void Compte::asgSolde (const double p_solde)
{
m_solde = p_solde;
}
unsigned int Compte::reqNoCompte () const{
return m_noCompte;
}
double Compte::reqTauxInteret() const{
return m_tauxInteret;
}
double Compte::reqSolde() const{
return m_solde;
}
string Compte::reqDescription() const{
return m_description;
}
string Compte::reqCompteFormate()const
{
ostringstream compteFormate;
return compteFormate.str();
}
但是我彈出以下錯誤:
Description Resource Path Location Type
undefined reference to « vtable for Compte » Compte.cpp /Travail Pratique 2 line 14 C/C++ Problem
對於.cpp文件中的構造函數,
Description Resource Path Location Type
undefined reference to « vtable for Compte » Compte.cpp /Travail Pratique 2 line 14 C/C++ Problem
最后,對於.header文件中的class Compte{
Description Resource Path Location Type
undefined reference to « vtable for Compte » Compte.h /Travail Pratique 2 line 16 C/C++ Problem
對於virtual ~Compte(){};
線。
我的代碼有什么問題,我該如何糾正?
您忘記了實現兩個虛擬方法,即克隆和calculerInteret。 這就是您的鏈接器抱怨的原因。 您的鏈接器沒有抱怨析構函數,但他在創建虛擬方法表時遇到了麻煩,因為缺少兩個標記為虛擬的方法。 只有鏈接程序才能找到類似的問題,因為從理論上講,這些方法甚至可以分布在多個源文件中。
如果您打算創建抽象方法,請執行以下操作:
virtual Compte* clone() const=0;
virtual const double calculerInteret()=0;
當然,您意識到您無法實例化具有抽象方法的類,對嗎?
在這種情況下,這不是問題,但對於查看此帖子的任何人來說可能是問題:
忘記虛擬析構函數上的主體會生成以下內容:
未定義對CYourClass的vtable的引用。
我正在添加一條注釋,因為錯誤消息具有欺騙性。 (這是在gcc版本4.6.3中使用的。)
因此添加:
Compte::~Compte()
{
}
到您的cpp
文件。
編輯1:正如Philip Stuyck指出的:如果缺少析構函數,那么您將有一個類似的錯誤,但是對於任何缺少的虛方法,您都可以使用它。 如果虛擬機是內聯的,則是或否無關緊要,如果是虛擬機,則只需要一個即可。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.