2009-07-25 4 views
3

이 작은 코드 스 니펫을 C++로 작성했으며 출력도 첨부되어 있습니다. 생성자가 두 번 호출되는 것을 볼 수있는 반면 생성자가 한 번만 호출되는 이유를 이해하지 못합니다. 내가, 기본 생성자 및 과부하 할당 연산자를 이해하는 것과C++ 생성자 호출

은 28

사람이에 대한 몇 가지 빛을 던져 주실 줄에서 호출해야합니다 :

1 #include <iostream> 
    2 using namespace std; 
    3 
    4 class ABC { 
    5 char c; 
    6 public: 
    7  ABC() { 
    8  cout << "default" << endl; 
    9  } 
10  ABC(char c) { 
11  this->c = c; 
12  cout << c << endl; 
13  } 
14  ~ABC() { 
15  cout << hex << this << " destructor " << c << endl; 
16  } 
17  void method() { 
18  cout << "method" << endl; 
19  } 
20  void operator= (const ABC& a) { 
21  cout << "operator" << endl; 
22  } 
23 
24 }; 
25 
26 int main() { 
27 ABC b('b'); 
28 ABC a = b; 
29 } 

Output in g++ version 4.0.1: 
~/src$ g++ test.cpp 
~/src$ ./a.out 
b 
0xbffff0ee destructor b 
0xbffff0ef destructor b 
+0

생성자 태그에 어떤 문제가 있습니까? – GManNickG

답변

11

코드는,이 정의를 바로 복사 생성자를 호출입니다있다 :

ABC(const ABC& a):c(a.c){ 
    cout << "copying " << hex << &a << endl; 
} 

그리고 당신은 다음과 같은 출력을 볼 수 갈까요 :

b 
copying 0x7fffebc0e02f 
0x7fffebc0e02e destructor b 
0x7fffebc0e02f destructor b 

기본적를 호출 할 경우 생성자와 할당 연산자를 사용하려면 두 개의 별도 문을 사용해야합니다.

ABC b('b'); 
    ABC a; 
    a = b; 
15
ABC a = b; 

이것은 acopy constructo입니다. r 할당 연산자가 아닙니다! 당신은 무엇을 당신이 가지고있는 것은 다음과 같이 다시 정의 할 수 컴파일러가 생성 한 :

ABC(const ABC& other) 
{ 
c = other.c; 
cout << c << " copy constructor" << endl; 
} 

당신이 정말로 당신이 당신의 클래스처럼 converstion 연산자를 추가하고 복사 생성자를 잊을 수 복사 생성자를 사용하지 않는 주장하는 경우!

operator char() 
{ 
    return c; 
} 
+0

더 나은 점은 초기화 목록을 사용할 수 있다는 것입니다. –

+0

그래, 이제 복사 생성자는 코드 –

+0

@litb에 'c'의 할당 연산자에 대한 호출을 포함합니다. 사실이 LOL입니다. – AraK

0

당신의

#include <iostream> 
using namespace std; 
class ABC { 
    char c; 
public: 

    ABC() { 
     cout << "default" << endl; 
    } 
     ABC(char c) 
     { 
      cout<<"parameterized constructor called\n";/////overloaded constructor called for the first line in main 
      this->c = c; 
      cout << c << endl; 
     } 
     ABC(ABC &c) 
     { 
      cout<<"Copy cons\n";//copy constructor is called for the second line in main 
     } 


     ~ABC() { 
      cout << hex << this << " destructor " << c << endl; 
     } 
     void method() { 
      cout << "method" << endl; 
     } 
     void operator= (const ABC& a) { 

     } 


    }; 


int main() 
{ 
     ABC b('b');//////here parameterized constructor is called i.e <ABC(char c)> 
     ABC a = b;/////////Here the copy constructor is called not the default one.(total 2 object created so the destructor is called twice!) 
} 

이 프로그램의 출력의 수정 된 코드를 살펴

parameterized constructor called 
b 
Copy cons 
0x7fff5fbff820 destructor � 
0x7fff5fbff828 destructor b 

지금 복사 생성자가 삼가지 경우 1.When 객체에서 호출되는 이유를 설명 할 수있다 되세요 in in initial 2. 개체가 매개 변수로 함수에 전달 된 경우 3. 개체가 함수에서 반환 된 경우.

자신의 복사 생성자를 지정하지 않으면 컴파일러는 비트별로 객체를 복사하는 자체 복사 생성자를 구현합니다. 코드에서 생성 된 두 객체를 추적 할 수없는 이유가 자신의 복사 생성자를 지정하지 않았습니다. 감사합니다.