gpt4 book ai didi

c++ - 模板和继承类中ostream重载的重定义错误

转载 作者:搜寻专家 更新时间:2023-10-31 02:24:43 25 4
gpt4 key购买 nike

我正在尝试在模板和继承类中重载 ostream 运算符,并且我一直在遵循一些提示 herehere ,但出现重定义错误。这是我的代码的复制:

#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));
^

为什么要重新定义友元函数?感谢您的宝贵时间。

附言。我正在使用 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/

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