我正在尝试在模板和继承类中重载 ostream 运算符,并且我一直在遵循一些提示 here和 here ,但我收到重新定义错误。这是我的代码的复制品:
#include <iostream>
enum type
{
A,
B
};
template <type T>
class base
{
protected:
virtual std::ostream& print(std::ostream& out) const =0;
};
template <type T>
class derived: public base<T>
{
protected:
virtual std::ostream& print(std::ostream& out) const
{
out<<"Hello World.\n";
return out;
}
public:
template <type S>
friend std::ostream& operator<<(std::ostream& out, const derived<S>& D)
{
return (D.print(out));
}
};
int main ()
{
#ifdef __NOT_WORKING__
derived<A> a;
std::cout<<a;
derived<B> b;
std::cout<<b;
#else
derived<A> a;
std::cout<<a;
#endif
return 0;
}
如果我只定义一个派生 A 类,一切正常,但如果我定义一个派生 A 和一个派生 B 类,我会从编译器中收到此错误:
test.cpp: In instantiation of 'class derived<(type)1u>':
test.cpp:38:20: required from here
test.cpp:27:30: error: redefinition of 'template<type S> std::ostream& operator<<(std::ostream&, const derived<S>&)'
friend std::ostream& operator<<(std::ostream& out, const derived<S>& D)
^
test.cpp:27:30: note: 'template<type S> std::ostream& operator<<(std::ostream&, const derived<S>&)' previously defined here
test.cpp: In instantiation of 'std::ostream& operator<<(std::ostream&, const derived<S>&) [with type S = (type)1u; type T = (type)0u; std::ostream = std::basic_ostream<char>]':
test.cpp:39:20: required from here
test.cpp:20:31: error: 'std::ostream& derived<T>::print(std::ostream&) const [with type T = (type)1u; std::ostream = std::basic_ostream<char>]' is protected
virtual std::ostream& print(std::ostream& out) const
^
test.cpp:29:37: error: within this context
return (D.print(out));
^
为什么要重新定义友元函数? 感谢您抽出时间。
PS。我正在使用 gcc49。最佳答案
替换
template <type S>
friend std::ostream& operator<<(std::ostream& out, const derived<S>& D)
{
return (D.print(out));
}
与
friend std::ostream& operator<<(std::ostream& out, const derived<T>& D)
{
return (D.print(out));
}
错误将会消失。
使用之前的定义,您正在尝试定义具有相同签名的新模板函数。
关于c++ - 模板和继承类中的 ostream 重载中的重新定义错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27719934/