不知道你的意思。 A(const A&)
是一个典型的copy-ctor,它具有对其唯一参数的“只读”访问权限。如果你传递任何const,一切都很好。如果你传递任何非const,对于ctor它变成const。如你所说,A a = 1
是一个转换ctor。 A other = a
是一个复制ctor。问题是什么?
关于您的问题的标题,在C++中没有公平将const
转换为非const
的方法。
class A
{
public:
int xx;
A(const A& other)
{
cout << "A cctor" << endl;
/* do some stuff */
// other is const here - you can only call its
// const methods and read all its data members
}
A(int x) : xx(x) {} /* conversion constructor */
// at this point, x is not const, but it's a copy
// of an object you've passed here, not the object itself
// you can change x, it just doesn't matter - you
// change the copy
};
int main()
{
A a = 1; // a is not const, 1 is passed "by value", since it's primitive type
A other = a; // a is not const, other is not const, a is passed by const reference
return 0;
}
听起来似乎合理。 –