奇数重复符号错误 [英] Odd duplicate symbols error

查看:107
本文介绍了奇数重复符号错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于学校项目,该课程被要求编写一个 String 类来模拟STL string 类。

For a school project, the class was asked to write a String class to mimic the STL string class.

我已经编写了所有的代码,但是链接器似乎被我的一个操作员所困扰。

I have all the code written, but the linker seems to be caught up on one of my operators.

有三个文件, String.h String.cpp test2.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 中:

This is odd, since the only place I define operator == is in 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 方法:

test2.cpp only has a bare main method:

#include "String.h"
using namespace std;

int main() {

}

所以,如果我在一个地方只定义 operator ==(const String& const const *),为什么说我有一个重复的符号?

So, if I only define operator ==(const String&, const char*) in one place, why does it say I have a duplicate symbol?

推荐答案

您提供了头文件中包含的操作符的定义 test2.cpp

您应该将定义移动到一个源文件中,并且只在头文件中提供声明。 p>

You provided the definitions of the operators in the header file which gets included by both String.cpp and test2.cpp.
You should move the definitions into one source file and only provide declarations in the header file.

// 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; 
}

这篇关于奇数重复符号错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆