2015-01-20 2 views
-5

저는 C++에 익숙하지 않고 현재 후위 연산자의 연산자 오버로딩을 배우고 있습니다. 아래의 프로그램에서 하나의 인자를 사용하면 결과가 좋지만 두 개의 인자가 있으면 프로그램이됩니다. 잘못된 출력을 표시합니다. 나는 사람들에게 내 문제를 해결하고 의심을 분명히 해달라고 요청한다.두 개의 인자에 대한 연산자 오버로드가 작동하지 않습니다.

#include<iostream> 
using namespace std; 
class num 
{ 
int a; 
public: 
num(int _a = 0) 
{ 
    a = _a; 
} 
num operator ++() 
{ 
    return a++; 
} 
num operator ++ (int) 
{ 
    return (a++); 
} 

void show() 
{ 
    cout << a << endl; 
} 
}; 

/* 
class num 
{ 
int a, b; 
public: 
num(int _a = 0, int _b = 0) 
{ 
    a = _a; 
    b = _b; 
} 

num operator ++() 
{ 
    a++; 
    b++; 
    return *this; 
} 

num operator ++ (int) 
{ 
    a++; 
    b++; 
    return *this; 
} 

void show() 
{ 
    cout << a << b << endl; 
} 
}; 

*/ 
int main() 
{ 
num ob(10); 
num z,y; 
ob.show(); 
z = ob++; 
z.show(); 

y = ++ob; 
y.show(); 
getchar(); 
return 0; 
} 

주석 처리 된 코드는 후위 교환 연산자를 사용하여 두 개의 숫자를 증가시키는 데 사용됩니다. 이 코드에는 잘못된 결과가 나타납니다.

+1

"잘못된 결과"를 정의하십시오. 프로그램 동작/출력에 대해 질문 할 때는 항상 예상 출력과 실제 출력을 게시하십시오. – Angew

+0

http://en.cppreference.com/w/cpp/language/operators 및 http://stackoverflow.com/questions/4421706/operator-overloading – sehe

+0

'return a ++; and return (a ++); '다른 결과를 돌려 주겠다고? – BeyelerStudios

답변

2

두 경우 모두 의 복사본을 이후에 (또는 시작시 주석 처리되지 않은 코드에서) 반환합니다. 후위 연산자는 객체 전에 증가하면 복사본을 반환해야합니다. 이 연산자는 접두사 연산자로 구현할 수 있습니다.

num copy = *this; 
++(*this); 
return copy; 
0

먼저 복사 한 다음 사본을 보냅니다.

#include<iostream> 
using namespace std; 
class num 
{ 
    int a; 
    public: 
    num(int _a = 0) 
    { 
     a = _a; 
    } 
    num operator++() 
    { 
     num t=(*this); 
     (this->a)++; 
     return t; 
    } 
    num operator++ (int) 
    { 
     a++; 
     return (*this); 
    } 

    void show() 
    { 
     cout << a << endl; 
    } 
}; 


int main() 
{ 
    num ob(10); 
    num z,y; 
    ob.show(); 
    z = ob++; 
    z.show(); 

    y = ++ob; 
    y.show(); 
    getchar(); 
    return 0; 
} 
관련 문제