2010-02-08 84 views
3

對於一個學校項目,課程被要求編寫String課程以模仿STL string課程。奇怪的重複符號錯誤

我已經編寫了所有的代碼,但鏈接器似乎被我的一個操作員追上。

中有三個文件,String.hString.cpptest2.cpp

Makefile看起來像

CC=gcc 
CXX=g++ 
CXXFLAGS+=-Wall -Wextra 
LDLIBS+=-lstdc++ 

all:test2 

test2:test2.o String.o 
test2.o:test2.cpp String.h 
String.o:String.cpp String.h 

make輸出以下:

g++ -Wall -Wextra -c -o test2.o test2.cpp 
g++ -Wall -Wextra -c -o String.o String.cpp 
g++ test2.o String.o -lstdc++ -o test2 
ld: duplicate symbol operator==(String const&, char const*)in String.o and test2.o 
collect2: ld returned 1 exit status 
make: *** [test2] Error 1 

這很奇怪,因爲唯一的地方我定義operator ==String.h

#ifndef MY_STRING_H 
#define MY_STRING_H 
#include <ostream> 
#include <istream> 

class String { 
    //... 
}; 

// ... operators ... 

bool operator ==(const String& left, const char* right) 
    { return left.compare_to(right)==0; } 
bool operator ==(const char* left, const String& right) 
    { return right.compare_to(left)==0; } 
bool operator ==(const String& left, const String& right) 
    { return left.compare_to(right)==0; } 

// ... other comparison operators ... 
#endif 

test2.cpp只有裸main方法:

#include "String.h" 
using namespace std; 

int main() { 

} 

所以,如果我只在一個地方定義operator ==(const String&, const char*),爲什麼它說我有一個重複的符號?

回答

6

您提供的定義,從而得到由兩個String.cpp測試2.cpp包含在頭文件中的運營商
您應該將定義移動到一個源文件中,並且只在頭文件中提供聲明

// in String.h: 
bool operator==(const String& left, const char* right); 

// in String.cpp: 
bool operator ==(const String& left, const char* right) { 
    return left.compare_to(right)==0; 
} 
+2

或者,使內聯頭文件中的定義。一般規則是頭文件中的任何函數定義都應該是內聯的,並且源文件中的定義不應該是內聯的。 – KeithB 2010-02-08 03:07:34