Re: Почему вызывается конструктор копирования?
От: VoidEx  
Дата: 05.10.07 21:16
Оценка:
Здравствуйте, na1s, Вы писали:

N>Явный косяк с логикой.

N>
N>#include <iostream>
N>using namespace std;
N>class A
N>{
N>public:
N>    A(){}
N>    A(const A &a){cout<<"1st";}
N>    A& operator =(A&){cout<<"2nd";}
N>};
N>int main()
N>{
N>    A b;
N>    A a=b;
N>    return 0;
N>}
N>

N>Почему печатает 1st, хотя должен 2nd? Этому есть разумное объяснение, почему сделано именно так?
Не должен.
12.8
A class object can be copied in two ways, by initialization (12.1, 8.5), including for function argument
passing (5.2.2) and for function value return (6.6.3), and by assignment (5.17). Conceptually, these two
operations are implemented by a copy constructor (12.1) and copy assignment operator (13.5.3).
2 A non-template constructor for class X is a copy constructor if its first parameter is of type X&, const X&,
volatile X& or const volatile X&, and either there are no other parameters or else all other
parameters have default arguments (8.3.6).106)
[Example:
X::X(const X&) and X::X(X&, int=1)
are copy constructors.

class X {
// ...
public:
X(int);
X(const X&, int = 1);
};
X a(1); // calls X(int);
X b(a, 0); // calls X(const X&, int);
X c = b; // calls X(const X&, int);

—end example]

8.5
A declarator can specify an initial value for the identifier being declared. The identifier designates an
object or reference being initialized. The process of initialization described in the remainder of 8.5 applies
also to initializations specified by other syntactic contexts, such as the initialization of function parameters
with argument expressions (5.2.2) or the initialization of return values (6.6.3).
initializer:
= initializer-clause
( expression-list )
initializer-clause:
assignment-expression
{ initializer-list ,opt }
{ }
initializer-list:
initializer-clause
initializer-list , initializer-clause
 
Подождите ...
Wait...
Пока на собственное сообщение не было ответов, его можно удалить.