开发者

C++ conversion operators

I know the deal .The compiler tries to convert one object into the other objects's type with the help of conversion operator .Two ways to do this .Constructor (Converts a class to the other) or conversion operator .So , this one is just to test if I am thorough with the concepts .The code below gives the error

using namespace std ;
class A
{
    int i ;
    public:
            A(int a=0){this->i=a;}
            A operator+(const A& b){
                    A c ;
                    return c(this->i+b.i);
            }
            void show()
            {
                    cout<<i<<endl;
            }
 };
int main()
{
    A a1(1),a2(2),a3;
    a3=a2+a1;
    a3.show();
    return 0;
 }

I guess the error is in the operator + .When I try to assign A(i) .There is no match for an operator which could create an A from an int .

But Then I see this A's constructor lurking behind .It can convert an int into an A .Suppose , it does convert int into an A.Then , the call becomes A(B开发者_如何学运维) .This is equivalent to the copy constructor .Hence , this call should work .But it doesn't .All in all , am pretty confused .

Please help .


In these two lines you are telling the compiler to construct an A object with the default constructor, then call its nonexistent operator () (int) and return its return value:

                A c ;
                return c(this->i+b.i);

Use either

A c(i + b.i);
return c;

or

return A(i + b.i);

On a side note, an example for an implicit conversion operator, for your class:

operator int () const
{
    return i;
}

But their use smells like bad design, and can cause bad stuff to happen, like implicit conversion to bool or a pointer. Use something else instead, like an int toInt () const member function.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜