I defined a class A

class A{
public:
  A(int){}
private:
  A(const A&);
  A& operator=(const A&);
};

I thought that since I give a constructor from int, the implicit construction is granted... Anyway while

A myA(7);

works fine, g++ gives me on this line:

A myA = 7;

the following error:

Test02.cpp: In function ‘int main(int, char**)’:
Test02.cpp:5:3: error: ‘A::A(const A&)’ is private
Test02.cpp:12:12: error: within this context

Another compiler instead is happy with this conversion. Where's the truth? How should I define A so that I get A myA = 7; working?

有帮助吗?

解决方案

GCC is right. A myA(7); is direct initialisation - it initialises myA using the constructor taking an int parameter.

A myA = 7; is copy initialisation - it initialises a temporary A object using the int constructor, and then initialises myA from this temporary using a copy constructor. Even though the copy will most likely be elided in practice, it must still be legal. And sinec the copy constructor is not accessible, it fails.

To make A myA = 7; work, you'll have to make the copy (or move) constructor accessible - which basically means making it public.

其他提示

g++ is right about this. The issue is that

A myA = 7;

is a copy initialization That means that, semantically, you have an implicit conversion to A on the RHS, and then a copy construction. The actual copy may be elided, but the copy constructor must still be accessible.

On the other hand,

A myA(7);

is a direct initialization. This only requires the converting constructor A(int).

More on direct initialization vs. copy initialization here.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top