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

标签 c++ templates inheritance ostream

我正在尝试在模板和继承类中重载 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));
                                     ^

为什么要重新定义友元函数? 感谢您抽出时间。

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/

相关文章:

c++ - 为什么析构函数不能是模板?

c++ - 模板类中嵌套类的问题

c++ - OpenCV QT,显示视频帧(不使用While循环)

c++ - 引用 const 对象但没有右值的函数

c++ - 从枚举器获取枚举类型

c++ - 如何在 C++ 中声明抽象类的 vector 列表?

ios - 继承 UIView 用于添加新逻辑或扩展 UIViewController

C++ 模板限制

C++ 传递对匿名结构的引用 - 你可以吗?

c++ - 使用指向派生类的指针作为模板参数时出错