未能使运算符重载<< (C ++)

时间:2014-04-27 15:09:46

标签: c++ operator-overloading operator-keyword

我正在尝试重载<< 。到目前为止没有运气。 这是我的重载实现:

struct Engineer{
    int id;
    int salary;
    bool hired;
public:
    Engineer(int _id, int _salary) : id(_id), salary(_salary), hired(false) {}

    std::ostream& operator<<(std::ostream& os)
    {
      return os << " " << id << std::endl;
    }
};

这是我尝试使用它:

void inorderTravel(AvlNode* root) {
    if(root == NULL) return;
    inorderTravel(root->left);
    std::cout << root->data;     // <- here
    inorderTravel(root->right);
}

行“std :: cout&lt;&lt; root-&gt; data;”唤起所有错误:

> Multiple markers at this line
>   - cannot convert 'root->AvlTree<Engineer,    IdKey>::AvlNode::data' (type 'Engineer') to type 'unsigned char'
>   - cannot convert 'root->AvlTree<Engineer,    IdKey>::AvlNode::data' (type 'Engineer') to type 'signed char'
>   - 'Engineer' is not derived from 'const std::basic_string<_CharT,    _Traits, _Alloc>'
>   - cannot convert 'root->AvlTree<Engineer,    IdKey>::AvlNode::data' (type 'Engineer') to type 'char'
>   - deduced conflicting types for parameter '_CharT' ('char' and       'Engineer')
>   - no match for 'operator<<' (operand types are 'std::ostream {aka    std::basic_ostream<char>}' and 'Engineer')
>   - candidates are:
>   - cannot convert 'root->AvlTree<Engineer,    IdKey>::AvlNode::data' (type 'Engineer') to type 'const char*'
>   - mismatched types 'const _CharT*' and 'Engineer'
>   - cannot convert 'root->AvlTree<Engineer,    IdKey>::AvlNode::data' (type 'Engineer') to type 'const unsigned char*'
>   - cannot convert 'root->AvlTree<Engineer,    IdKey>::AvlNode::data' (type 'Engineer') to type 'const signed char*'

2 个答案:

答案 0 :(得分:2)

您定义了运算符std::ostream& Engineer::operator<<(std::ostream&) - 因此,left << right这样的表达式的左操作数必须是Engineer类型,右侧操作数类型为std::ostream& ... < / p>

您可以在Engineer类中将正确的运算符定义为友元函数,如下所示:

friend std::ostream& operator<<(std::ostream& out, Engineer const& self)
{ return out << " " << self.id << std::endl; }

答案 1 :(得分:1)

这不是operator<<的正确定义。此运算符应将 second 参数作为对要尝试打印的类的实例的const引用。使用您的定义有一个隐含的第一个参数。无法在类中定义operator<<,通常将其实现为友元函数。像这样:

struct Engineer{
  //... other code
  friend std::ostream& operator<<(std::ostream& os, const Engineer& e);
};

std::ostream& operator<<(std::ostream& os, const Engineer& e)
{
  return os << " " << id << std::endl;
}