0

簡単なクラス ライブラリを作成する必要があります。との 2 つのクラスがElementありPermutationます。

ファイル Element.h

#ifndef ELEMENT_H
#define ELEMENT_H

class Element
{
public: 
    virtual ~Element()=0;
    virtual bool IsEven()=0;
    virtual bool IsNeutral()=0;
};

#endif

ファイル順列.h

#ifndef PERMUTATION_H
#define PERMUTATION_H

#include "Element.h"

class Permutation: public Element
{
private:
    int* numbers; 

public:
    const int k;
    Permutation(const int, int*); 
    Permutation(const int); 
    Permutation(); 
    ~Permutation(); 
    int NumberOfInversions(); 
    bool IsEven(); 
    bool IsNeutral(); 

    friend Permutation operator+(const Permutation&, const Permutation&); 
    friend Permutation operator-(const Permutation&); 
};

#endif

そして、クラス Permutation を実装する Permutation.cpp があります。クラス要素は抽象的であるため、実現された .cpp ファイルはありません。そこで、クラス Permutation を使用する簡単なテスト プログラム (main を含む) を書きたいと思います。プロジェクトをどのようにビルドすればよいですか? Linux プラットフォームで g++ コンパイラを使用しています。

動作しない Makefile は次のとおりです。

all: permutation_test

permutation_test: fuf.o Permutation.o 
    g++ fuf.o Permutation.o -o permutation_test
fuf.o: fuf.cpp
    g++ -c fuf.cpp 
Permutation.o: Permutation.cpp 
    g++ -c Permutation.cpp 

clean:
   rm -rf *o permuatation_test

(fuf.cpp には main メソッドが含まれています。)
エラー:
Permutation.o: 関数内 «Permutation::Permutation(int, int*)»:
Permutation.cpp:(.text+0xd): 未定義の参照 «Element::Element( )»
Permutation.o: 関数内 «Permutation::Permutation(int)»:
Permutation.cpp:(.text+0x3c): 未定義参照 «Element::Element()»
Permutation.cpp:(.text+0xac):未定義参照 «Element::~Element()»
Permutation.o: 関数内 «Permutation::Permutation()»:
Permutation.cpp:(.text+0xcd): 未定義参照 «Element::Element()»
Permutation.o : 関数内 «Permutation::~Permutation()»:
Permutation.cpp:(.text+0x11e): 未定義の参照 «Element::~Element()»
collect2: エラー: ld が 1 終了ステータスを返しました

それは今動作します。返信ありがとうございます。クラスElementの純粋な仮想デストラクタを仮想および削除されたコンストラクタに置き換えました

4

1 に答える 1

0

デストラクタを純粋仮想にしたとしても、定義を提供する必要があります。そうしないと、サブクラスのデストラクタはそれを呼び出すことができません。

コンパイル エラーを修正するには、追加します。

inline Element::~Element() {}

Element.h に。

(純粋仮想関数の定義を提供できることはあまり知られていません。)

Herb Sutter による古いGuru of the Week で、純粋な仮想の定義を提供することについていくつかの議論があります。

一方
で、この場合、純粋な仮想デストラクタを持つことはほとんど意味がないと言わざるを得ません。他に何もないときにクラスを抽象化する以外に、その用途は考えられません。仮想関数。

最良の解決策はElement、混乱を引き起こす以外の目的を果たさないため、 のデストラクタを完全に破棄することです。

于 2012-11-14T18:39:47.733 に答える