0

私は単純なクラスのヘッダーファイルを持っています:

> cat Algorithms.hh
#ifndef Algorithms_hh
#define Algorithms_hh
#include<vector>
class Algorithms
{
public:

Algorithms();
void BubbleSort();

std::vector<int> myarray;

};
#endif

次に、対応するcファイル:

> cat Algorithms.cc
#include <iostream>
#include <vector>
#include "Algorithms.hh"

Algorithms::Algorithms()
{
myarray.push_back(0);
}


void Algorithms::BubbleSort()
{
      int i, j, flag = 1;    // set flag to 1 to start first pass
      int temp;             // holding variable
      int numLength = myarray.size(); 
      for(i = 1; (i <= numLength) && flag; i++)
     {
          flag = 0;
          for (j=0; j < (numLength -1); j++)
         {
               if (myarray[j+1] > myarray[j])      // ascending order simply changes to <
              { 
                    temp = myarray[j];             // swap elements
                    myarray[j] = myarray[j+1];
                    myarray[j+1] = temp;
                    flag = 1;               // indicates that a swap occurred.
               }
          }
     }
}
>

そして主な機能:

> cat algo2.cc
#include <iostream>
#include <vector>
#include "Algorithms.hh"

using namespace std;

int main(int argc,char **argv)
{

Algorithms *arr=new Algorithms();
arr->myarray.push_back(1);
arr->myarray.push_back(2);
arr->myarray.push_back(100);
return 0;
}

> 

メインをコンパイルすると、次のエラーが発生します。

> CC algo2.cc 
Undefined                       first referenced
 symbol                             in file
Algorithms::Algorithms()              algo2.o
ld: fatal: Symbol referencing errors. No output written to a.out

誰かが私がどこが間違っているのか教えてもらえますか?

4

2 に答える 2

2

これはリンカエラーです。リンカは、クラスのコンストラクタの定義が見つからないと言っていますAlgorithms。次のコマンドでコンパイルする必要があります。

CC Algorithms.cc algo2.cc 

エラーの前にあるため、リンカーエラーであることがわかりld:ます。

そしてもちろん、Kerrek SBが述べているように、コンストラクターを前に付けずに宣言する必要がありますAlgorithms::...

于 2012-09-03T07:53:11.113 に答える
0

両方の.ccファイルをコンパイルに含めるのを忘れただけです。

cc algo2.cc Algorithms.cc

次のような宣言を含むヘッダーファイルをインクルードする場合

#include "Algorithms.hh"

また、実装、.cまたは.libでの定義を提供する必要があります。または、定義を含むライブラリを動的にロードします。あなたの場合、ライブラリはAlgorithms.ccなので、コンパイル段階に追加してから、両方の一時オブジェクトファイルを追加します。

Algo2.a + Algorithms.a

に行きます

a.out
于 2012-09-03T08:02:39.983 に答える