开发者

Why cant i call 'explicit C(const C&)'?

Heres the link to code and 开发者_如何学Gothe error

I dont understand why the line return (const C&)cc; doesnt work.

Heres a paste of code and error

#include <stdio.h>

class C 
{
public:
    int i;
    explicit C(const C&)   // an explicit copy constructor
    {
        printf("\nin the copy constructor");
    }
    explicit C(int i )   // an explicit constructor
    {
        printf("\nin the constructor");
    }

    C()
    {
        i = 0;
    }
};

class C2
{
public:
    int i;
    explicit C2(int i )   // an explicit constructor
    {
    } 
};

C f(C c)
{   // C2558
//    c.i = 2;
//    return c;   // first call to copy constructor
C cc;
return (const C&)cc;
}

void f2(C2)
{
}

void g(int i)
{
//    f2(i);   // C2558
    // try the following line instead
     f2(C2(i));
}

int main()
{
    C c, d;
    d = f(c);   // c is copied
}

Output:

In function 'C f(C)': Line 36: error: no matching function for call to 'C::C(const C&)' compilation terminated due to -Wfatal-errors.


Line 36 requires a implicit call of the copy constructor, which you have declared explicit for some reason. Remove the explicit on the copy and you will be fine. It makes sense to have it on C::C(int).


Examples of calling the explicit copy-constructor:

  • http://ideone.com/bV4S7
  • http://ideone.com/G0OYi

Of course, pass-by-value and return-by-value always call the copy constructor implicitly, so declaring the copy constructor explicit will prevent this (not necessarily a bad thing).


Try:

return C(cc);

This is an explicit call to the copy constructor. Casting to a reference is not.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜