2014-03-06 3 views
1

사용자가 배열에 배치 된 임의의 숫자를 쓰고 그에게 표시되는 C++에서 응용 프로그램을 만들었고 복사 생성자를 사용하여 입력 된 시간이 다시 표시됩니다 . 하지만 여기서 문제는 복사 기능이 실행되지만 정보를 표시하지 않는다는 것입니다. 당신은 이동 생성자에서 데이터 멤버 세를 복사하는 것을 잊었다C++ 복사 생성자 런타임 오류

#include <iostream> 
#include <string> 
using namespace std; 

class Identity{ 
protected: 
    int* arry_int; 
    int ages; 
    Identity(){} //private default constructor 
public: 
    Identity(int repeated_number){ //overloaded constructor 
     ages = repeated_number ; 
     arry_int = new int [ages]; 
    } 
    void getAge(){ //getting age form the user 
     for (int i = 0; i < ages; i++){ 
      cout << "Enter age[" << i << "]: "; 
      cin >> arry_int[i]; 
     } 
    } 
    void printAge(){ 
     cout << "Friend's ages" << endl; 
     cout << "-----------------" << endl; 
     for (int i = 0; i < ages; i++){ 
      cout << arry_int[i] << endl; 
     } 
    } 
    //move copy constructor 
    Identity(Identity&& cpy){ 
     cout << "Declaring move constructor" << endl; 
     arry_int = cpy.arry_int; 
     cpy.arry_int = NULL; 
    } 
    //move assignment operator 
    Identity& operator=(Identity&& cpy){ 
     cout << "Declaring move assignment operator" << endl; 
     if (this != &cpy){ 
     delete arry_int; 
     arry_int = cpy.arry_int; 
     cpy.arry_int = NULL; 
     } 
     return *this; 
    } 
    ~Identity(){ 
     delete arry_int; 
    } 
}; 

int main(){ 
    string nemesis; 
    Identity iden(5); 
    iden.getAge(); 
    iden.printAge(); 
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); 
    cout << "Enter your nemesis name: " << endl; 
    getline(cin,nemesis); 
    //nemesis stealing your identit 
    Identity stolen(move(iden)); 
    cout << "Now " << nemesis << " stole your friend's age and used it against you" << endl; 
    stolen.printAge(); 
    system("pause"); 
    return 0; 
} 
+0

복사 생성자와 이동 생성자는 고유합니다. 용어를 섞어 쓰지 마십시오. 그것은 단지 다른 사람들을 혼란스럽게합니다. – Brian

답변

3

: 다음은 내 코드입니다.

이 있어야합니다

//move copy constructor 
Identity(Identity&& cpy){ 
    cout << "Declaring move constructor" << endl; 
    arry_int = cpy.arry_int; 
    cpy.arry_int = NULL; 
    ages = cpy.ages; 
} 

동일 이동 할당 연산자 또한 소멸자

~Identity(){ 
     delete []arry_int; 
} 

로 정의되어야한다

//move assignment operator 
Identity& operator=(Identity&& cpy){ 
    cout << "Declaring move assignment operator" << endl; 
    if (this != &cpy){ 
    delete arry_int; 
    arry_int = cpy.arry_int; 
    cpy.arry_int = NULL; 
    ages = cpy.ages; 
    } 
    return *this; 
} 

유효합니다 그리고 그것은 알 수없는 이유를 기본 생성자를 protected로 선언했습니다.

+0

모스크바에서 감사합니다 @Vlad 당신의 설명은 훌륭합니다. 그리고 한가지 만 더 물어보고 싶습니다. 이미 복사 생성자가 있고 복사 할당 연산자가있을 때 이동 생성자가 필요한 이유는 무엇입니까? 고마워 – user3264250

+0

@ user3264250 클래스에 복사 생성자와 복사 할당 연산자가 없습니다. 더 정확하게 말하면 삭제 된 것으로 정의됩니다. 일반적인 경우를 의미한다면 이동 생성자/할당은 단순히 대상 객체에 위임되므로 리소스를 사용하여 수많은 연산을 탈출 할 수 있습니다. –