2014-04-27 159 views
2

我试图超载< <。到目前为止没有运气。 这里是我的过载实现:未能超载运算符<<(C++)

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 ::法院< <根 - >数据;”唤起所有错误:

> 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*' 
+0

什么是'AvlNode'的定义是什么? –

+0

什么是'root-> data'? – 0x499602D2

+0

[运算符重载]的可能重复(http://stackoverflow.com/questions/4421706/operator-overloading) –

回答

1

这不是operator<<的正确定义。此运算符应该为参数为您试图打印的类的实例的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; 
} 
+0

非常感谢!它一直在窃听我几个小时! –

+0

*运算符<<不能在类中定义* - 这是全部真相吗?如果是的话,为什么? – Wolf

+0

@wolf从OP的问题来看,这个想法是使用'operator <<'输出到一个流。如果这是需要的,应按我描述的方式声明运营商。这意味着这个运算符的第一个参数应该是一个'ostream&',并且所有的类方法都有一个类类型的隐式第一个参数,所以不可能在类中声明这样的方法。具有其他操作数类型的'operator <<'仍可以声明,但在OP描述的情况下不会使用它。 –

2

您定义的操作符std::ostream& Engineer::operator<<(std::ostream&) - 所以像left << right表达式的左操作数必须是Engineer类型和std::ostream&类型的右操作数的...

您可以定义权运营商在你的Engineer类友元函数,像这样:

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

*左边的参数*似乎有点误导性 – Wolf

+0

@Wolf澄清了含义 –

+0

更改顺序如何解决方法:先解决方法,稍后再解决失败的方法?我发现重点在于[当前版本的答案](http://stackoverflow.com/revisions/23325060/2)中的错误。 – Wolf