隐式运算符bool()没有响应我的调用

时间:2016-06-17 17:37:05

标签: c++ operator-overloading

我正在测试模板:

_Tarray<int, char> out;
  cout << out; 

所以,我这样驾驶它:

operator<<

这是我的重载template<typename T, typename U> ostream& operator<< (ostream& os, const _Tarray<T, U>& var){ //now i expect operator bool() to be called here if(var){os << " Yes !";} //and bool is not being called. my compiler (g++) is angry else{cout << " No !";} return os; }

./template.h: In instantiation of 'std::ostream& operator<<(std::ostream&, const _Tarray<T, U>&) [with T = int; U = char; std::ostream = std::basic_ostream<char>]':
./template.h:128:41:   required from 'void var_dump(const T&) [with T = _Tarray<int, char>]'
functions.cpp:12:21:   required from here
./template.h:122:5: error: passing 'const _Tarray<int, char>' as 'this' argument discards qualifiers [-fpermissive]
     if(var){os << "heheheheh";}
     ^
./template.h:73:5: note:   in call to '_Tarray<Key, char>::operator bool() [with Key = int]'

哪个给了我

over()

为什么它会给我一个编译器错误,我该怎么做才能修复它?

2 个答案:

答案 0 :(得分:4)

operator<< varconst。由于它是const,您只能调用const合格的成员函数。由于您的operator bool未标记为const,因此您无法使用它。要解决此问题,请将operator bool更改为

operator bool() const {cout << " just testing"; return false;} 

答案 1 :(得分:4)

varconst _Tarray<T, U>&。这里的重要信息是const,这意味着,如果var修改了var 的属性,则无法从operator bool调用任何函数。

编译器不知道你的operator bool没有修改任何东西,所以它失败了。您必须明确声明您的_Tarray不会修改const,方法是将该功能指定为//Note the 'const', operator bool own't change anything, so the call from a const //instance is legal operator bool() const { std::cout << "Just testing\n"; return false; }

{{1}}