0

プロジェクトをファイルに分割することに決めている間、私は自分のプロジェクトに取り組んでいました。しかし、私はこのような問題に悩まされ、グーグルで見つけたすべてのアドバイスは、私が正しく行っている両方のオブジェクトファイルをリンクするのを忘れることについてでした(少なくとも私はそう思います)。

Makefile:

test : class.o main.o
 g++ class.o main.o -o test.exe

main.o : main.cpp
 g++ main.cpp -c

class.o : class.cpp
 g++ class.cpp -c

main.cpp

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

int main() {
 Trida * t = new Trida(4);
 t->fce();
 return 0;
}

class.h

#ifndef CLASS
#define CLASS
class Trida {
private:
 int a; 
public:
 Trida(int n); 
 void fce();
};
#endif

class.cpp

#include <iostream>

using namespace std;

class Trida {
private:
 int a;

public:
 Trida(int n) {
  this->a = n;
 } 

 void fce() {
  cout << this->a << endl;
 }
};

エラーメッセージ:

gwynbleidd@gwynbleidd-pc:~/Skola/test$ make
g++ class.cpp -c
g++ main.cpp -c
g++ class.o main.o -o test.exe
main.o: In function `main':
main.cpp:(.text+0x26): undefined reference to `Trida::Trida(int)'
main.cpp:(.text+0x54): undefined reference to `Trida::fce()'
collect2: ld returned 1 exit status
make: *** [test] Error 1
4

2 に答える 2

4

これがあなたが間違ったことです。class.cppでは、class.hで作成したクラスを実装するのではなく、新しいTridaクラスを再作成します。class.cppは次のようになります。

#include <iostream>
#include "class.h"

using namespace std;

Trida::Trida(int n)
{
  this->a = n;
}

void Trida::fce() { cout << this->a << endl; }

そして実際には、コンストラクターで割り当てではなく初期化を使用する必要があります。

Trida::Trida(int n) : a(n) {}
于 2011-01-08T05:15:52.570 に答える
0

クラスをtrida2回定義しています(ヘッダーファイルclass.hとソースファイルでclass.cpp)class.cppファイルは次のようになります。

#include <iostream>
#include "class.h" //include "class.h"
using namespace std;

Trida::Trida(int n):a(n) //Initialization list
{
} 

void Trida::fce()
{
  cout << this->a << endl;
}
于 2011-01-08T05:18:20.417 に答える