gpt4 book ai didi

c++模板特化 - 链接器错误多个定义

转载 作者:IT老高 更新时间:2023-10-28 23:17:35 26 4
gpt4 key购买 nike

我今天在这里的第三个问题 ;-),但我对 c++ 模板编程和运算符重载真的很陌生。

我正在尝试以下方法:

终端日志.hh

//snipped code

class Terminallog {
public:

Terminallog();
Terminallog(int);
virtual ~Terminallog();

template <class T>
Terminallog & operator<<(const T &v);
template <class T>
Terminallog & operator<<(const std::vector<T> &v);
template <class T>
Terminallog & operator<<(const T v[]);
Terminallog & operator<<(const char v[]);

//snipped code
};

//snipped code
template <class T>
Terminallog &Terminallog::operator<<(const T &v) {
std::cout << std::endl;
this->indent();
std::cout << v;
return *this;
}

template <class T>
Terminallog &Terminallog::operator<<(const std::vector<T> &v) {
for (unsigned int i = 0; i < v.size(); i++) {
std::cout << std::endl;
this->indent();
std::cout << "Element " << i << ": " << v.at(i);
}
return *this;
}

template <class T>
Terminallog &Terminallog::operator<<(const T v[]) {
unsigned int elements = sizeof (v) / sizeof (v[0]);
for (unsigned int i = 0; i < elements; i++) {
std::cout << std::endl;
this->indent();
std::cout << "Element " << i << ": " << v[i];
}
return *this;
}

Terminallog &Terminallog::operator<<(const char v[]) {
std::cout << std::endl;
this->indent();
std::cout << v;
return *this;
}
//snipped code

试图编译这段代码,它给了我一个链接器错误:

g++ src/terminallog.cc inc/terminallog.hh testmain.cpp -o test -Wall -Werror 
/tmp/ccifyOpr.o: In function `Terminallog::operator<<(char const*)':
testmain.cpp:(.text+0x0): multiple definition of `Terminallog::operator<<(char const*)'
/tmp/cccnEZlA.o:terminallog.cc:(.text+0x0): first defined here
collect2: ld returned 1 exit status

因此,我目前正在将头撞到墙上,寻找解决方案。但我在墙上找不到...

如果有人能告诉我我的错误,那就太好了

非常感谢

ftiaronsem

最佳答案

这个函数

Terminallog &Terminallog::operator<<(const char v[]) {
std::cout << std::endl;
this->indent();
std::cout << v;
return *this;
}

不是模板,而是常规的成员函数。如果此 .h 文件包含在多个 .cpp 过滤器中,则会导致您看到的多重定义错误。如果你声明它inline,编译器将允许多个定义并且你的错误应该被修复。

inline
Terminallog &Terminallog::operator<<(const char v[]) {

关于c++模板特化 - 链接器错误多个定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5453361/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com