【问题标题】:problems when trying to overload << operator in c++11尝试在 C++11 中重载 << 运算符时出现问题
【发布时间】:2014-06-21 20:51:36
【问题描述】:

我正在尝试编写 C++ 优先队列实现。

这是优先队列元素的类:

template <class Priority, class T>
class PriorityQueueElement {

public:
Priority priority;
T* data;

private:
    PriorityQueueElement* next ;
public:

    PriorityQueueElement( const Priority& priority,T data ) :
        priority(priority) ,data(&data) , next(NULL){
    }
    // ... other functions .. //
    template <class P, class Y>
    friend ostream& operator<<(ostream& os ,const PriorityQueueElement<P,Y>& element);

}; 

和功能:

template<class Priority, class T>
ostream& operator<<(ostream& os ,const PriorityQueueElement<Priority,T>& elemen){
        return os << "[" << elemen.getPriority() << "," << elemen.getData( ) << "]";
}

我得到了错误:

Multiple markers at this line
    - template argument deduction/substitution failed:
    - template<class Priority, class T> std::ostream& mtm::operator<<(std::ostream&, const 
 mtm::PriorityQueueElement<Priority, T>&)
Multiple markers at this line
    - required from 'std::ostream& mtm::operator<<(std::ostream&, const mtm::PriorityQueueElement<Priority, T>&) [with Priority = int; T = int; std::ostream = 
 std::basic_ostream<char>]'
    - required from 'std::ostream& mtm::operator<<(std::ostream&, const mtm::PriorityQueueElement<Priority, T>&) [with Priority = double; T = Student; 
 std::ostream = std::basic_ostream<char>]'

如果我尝试使用:

template <class Priority,class T>

我收到一个关于在类本身中隐藏模板的错误

感谢您的帮助!

【问题讨论】:

  • 您能否提供一个最小的完整示例,以便我们重现该问题?
  • 您的构造函数正在获取按值传递参数的地址并将其存储在类成员中。那……糟糕。

标签: c++ templates c++11 operator-overloading iostream


【解决方案1】:

我复制了你的代码并稍作修改(用于测试)

template<class Priority, class T>
    ostream& operator<<(ostream& os, const PriorityQueueElement<Priority, T>& elemen)
    {
        return os << "[" << elemen.priority << "," << *elemen.data << "]";
    }

它的工作原理,我主要说:

PriorityQueueElement<int, const char*> x( 1, "fsdfsdfsd" );
cout << x;

它给了我输出:[1,fsdfsdfsd]

在 Visual Studio 2013 上测试。 问题可能在其他地方

【讨论】:

    猜你喜欢
    • 2014-03-18
    • 2021-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-14
    • 2014-04-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多