2011-09-01 86 views
1

考虑以下几点:复制构造函数将const从const转换为非const?

class A 
{ 
public: 
    int xx; 
    A(const A& other) 
    { 
     cout << "A cctor" << endl; 
     /* do some stuff */ 
    } 

    A(int x) : xx(x) {} /* conversion constructor */ 

    }; 


int main() 
{  
    A a = 1; 
    A other = a; 
    return 0; 
} 

那么,是否可以说,从CCtor常量到非const转换在这种情况下(也一般)?

谢谢你,罗恩

+0

听起来似乎合理。 –

回答

0

不知道你的意思。 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; 
} 
0

构造函数初始化一个新的副本。从常量复制没有问题。

不涉及转换。

+0

我的意思是来自一个存在的对象(同一个类)。此外,如果我这样做:\t A(A&其他) \t { \t \t COUT << “A cctor” << ENDL; \t \t/*做一些东西*/ \t} //作为类的CCtor,那么我会得到一个编译错误.. –

+0

@Ron_s再次,没有转换涉及。你只是声明你不会改变参数(这是有道理的,你为什么要改变副本的来源?)。 –

+0

如果你的拷贝构造函数使用非const引用参数Ron,你为什么会得到编译错误?在您的示例中,您从中复制的对象是非常量。 –

0

你是什么意思CCtor从const转换为非const

如果你的意思是,非const对象是通过调用copy-constructor从const对象创建的,那么是的。但是,这并不意味着const-object本身在copy-constructor(或者在调用站点)变成非const。它只意味着通过复制将现有对象作为常量引用复制到复制构造函数,从而创建新构造的对象

0

否复制构造函数通过将另一个类对象作为参数来创建类对象的副本。

由于为了构造传递的新对象,因为参数不需要修改,所以它作为const传递。

5

复制构造函数创建一个现有对象的新副本,该对象可能是也可能不是const。在A::A(const A& other)中的常量只是说我们不会在复制ctor中更改other。事实上,如果你试图修改其他内部的编译器会呻吟你。

创建的对象也可能是或不是const,具体取决于您如何声明它。

0

不,它不转换为非const对象。试想一下:

A a(42); 
const A another = a; 

这里,anotherconst对象,从非const对象创建的。

但是,更重要的是,10构造函数从现有构造函数创建新对象。无论新对象是否为const,都不依赖于现有对象。旧的/新的对象的所有四种可能的组合都可能。const/non- const旧/新对象是可能的。

0

在该A(int)构造转换从intA感,是的,它是真的,你的拷贝构造函数A(const A&)“转换”从const AA。对于这个问题,它也将非const const A“转换”为A,因为const引用参数可以绑定到其中任一个。

而且因为同一个构造函数用于创建一个const对象,以创建一个非const一个,那拷贝构造函数也可以“转换”从Aconst Aconst A

我已经在引号中使用了“convert”,仅仅是因为从一个类型转换到它自己或者cv合格版本本身可能是一个令人困惑的术语使用,通常你只是称之为“复制”而不是转换。

构造函数参数也可以绑定到派生类A的实例,所以您可能会说它将派生类转换为A。这通常称为“切片”。

严格地说,它不是复制ctor本身可以转换任何东西,而是转换为A(无论是强制转换还是隐式转换)的确依赖于使用匹配的构造函数。所以我想建设者可以声称很大一部分功劳。