2017-12-12 1 views
-7

나는이 클래스를 가지고 있으며, ++ c가 생성 될 때 어떤 일이 일어날 지 이해할 수 없다. 그리고 이것이 * 무엇을 의미합니까? 미안해, 내 영어로.사전 증가 작업 중에 객체는 어떻게됩니까?

class Cls{ 

int i; 
public: 
    Cls(int i=8):i(i){cout<<'A';} 
    Cls(const Cls &t):i(t.i){cout<<'B';} 
    ~Cls(){cout<<'C';} 
    void af(){cout<<i;} 
    Cls operator+(Cls &t){return Cls(i+t.i);} 
    Cls operator++(){i++; return *this;} 
    Cls& operator--(){--i; return *this;} 
    operator int(){cout<<'D'; return i;} 

    }; 

    int main(){ 

     Cls c; cout <<","; //Here the constructor will print A 
     ++c; cout <<","; // here? 
     c.af(); cout <<","; //This will print 9 

      //Then the destructor will print C. 
     return 0; 
    } 

실제 출력은 다음과 같습니다

A,BC,9,C 

나는 그것이 인쇄해야 기대 :

A,,9,C 

BC가 인쇄되는?

+1

이름을 선택하면 조금 혼란 스럽습니다. 나는 처음에 당신이 C++ 객체가 생성되었을 때 어떻게되는지를 묻고 있다고 생각했습니다. –

+0

'this'는 "this pointer"로 알려져 있습니다. – Yashas

+0

++ c가 생성되었습니다? –

답변

1

선 증가 연산자 메서드는 개체를 반환합니다. 어느 쪽이 생성자를 호출하고, 나중에는 소멸자입니다. 당신은 또한 당신이 최적화 수준을 높일 경우 쉽게 할 수 다음 "BC"를 사용하여 컴파일러로 사라질 가능성이 있는지주의해야한다

Cls& operator++(){i++; return *this;} 
    ^^^ To return the object by reference (and thus avoid construction/destruction). 

: 당신이 일반적으로이를 작성합니다

Cls operator++(){i++; return *this;} 
^^^ return by value. 
    Means you need to be able to copy construct "Cls" 

주 복사 작업을 최적화로 "제거"합니다.

관련 문제