简体   繁体   中英

Why does overload ! operator need a const return

g++ 4.5.3 (cygwin)

class SlipDatum {
public:
   bool operator!();
   long operator~();
}

bool SlipDatum::operator!() { }
long SlipDatum::operator~() { }

Operator!() expects prototype: const bool operator!();

but operator~() works with no expectations. Any reaon why?

The compiler error is:

SlipDatum.cpp:104:15: error: prototype for 'const slip::BOOL slip::SlipDatum::operator!()' does not match any in class 'slip::SlipDatum' SlipDatum.h:15295:18: error: candidate is: bool slip::SlipDatum::operator!()

It is hard to figure out what you mean exactly, but in many cases missing ; after class definition can lead to various bizarre and confusing error messages. I can't reproduce yours though in my version of GCC.

Anyway, add a ; at the end of class definition.

class SlipDatum {
public:
   bool operator!();
   long operator~();
};

bool SlipDatum::operator!() { return false; }
long SlipDatum::operator~() { return 0; }

int main() {
  SlipDatum unused;
}

this code compiles fine in gcc 4.3.4 gcc 4.5.1 and gcc 4.7.2

Either you found a strange bug in gcc 4.5.3 (cygwin), or your problem is you failed to actually return from a function that expects a return value, or your question is badly formed, or your error is otherwise in the difference between your post and my answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM