constructor - C++ conversion operators -
i know deal .the compiler tries convert 1 object other objects's type of conversion operator .two ways .constructor (converts class other) or conversion operator .so , 1 test if thorough concepts .the code below gives error
using namespace std ; class { int ; public: a(int a=0){this->i=a;} operator+(const a& b){ c ; return c(this->i+b.i); } void show() { cout<<i<<endl; } }; int main() { a1(1),a2(2),a3; a3=a2+a1; a3.show(); return 0; }
i guess error in operator + .when try assign a(i) .there no match operator create an int .
but see a's constructor lurking behind .it can convert int .suppose , convert int a.then , call becomes a(b) .this equivalent copy constructor .hence , call should work .but doesn't .all in , pretty confused .
please .
in these 2 lines telling compiler construct object default constructor, call nonexistent operator () (int) , return return value:
c ; return c(this->i+b.i);
use either
a c(i + b.i); return c;
or
return a(i + b.i);
on side note, example implicit conversion operator, class:
operator int () const { return i; }
but use smells bad design, , can cause bad stuff happen, implicit conversion bool or pointer. use else instead, int toint () const
member function.
Comments
Post a Comment