접미사 a ++와 접두사 ++ a에 대해 두 가지 다른 방법으로 operator ++를 오버로드하는 방법은 무엇입니까?
접미사 a++
와 접두사에 대해 두 가지 다른 방법으로 operator ++를 오버로드하는 방법은 ++a
무엇입니까?
다음과 같이 표시되어야합니다.
class Number
{
public:
Number& operator++ () // prefix ++
{
// Do work on this. (increment your object here)
return *this;
}
// You want to make the ++ operator work like the standard operators
// The simple way to do this is to implement postfix in terms of prefix.
//
Number operator++ (int) // postfix ++
{
Number result(*this); // make a copy for result
++(*this); // Now use the prefix version to do the work
return result; // return the copy (the old) value.
}
};
차이점은의 오버로드에 대해 선택한 서명에 있습니다 operator ++
.
C ++ FAQ의이 주제에 대한 관련 기사에서 인용되었습니다 (자세한 내용은 여기로 이동).
class Number { public: Number& operator++ (); // prefix ++: no parameter, returns a reference Number operator++ (int); // postfix ++: dummy parameter, returns a value };
추신 : 이 사실을 알게되었을 때 처음에 보았던 것은 더미 매개 변수 였지만 실제로는 다른 반환 유형이 더 흥미 롭습니다. 그들은 왜 일반적인++x
것보다 더 효율적인 것으로 간주 되는지 설명 할 수 있습니다 .x++
유형 T에 대해 두 가지 (접두사 / 접미사) ++ 연산자를 오버로드하는 두 가지 방법이 있습니다.
개체 방법 :
"일반적인"OOP 관용구를 사용하는 가장 쉬운 방법입니다.
class T
{
public :
T & operator++() // ++A
{
// Do increment of "this" value
return *this ;
}
T operator++(int) // A++
{
T temp = *this ;
// Do increment of "this" value
return temp ;
}
} ;
개체 비 멤버 함수 :
이것은이를 수행하는 또 다른 방법입니다. 함수가 참조하는 객체와 동일한 네임 스페이스에있는 한 컴파일러가 처리 ++t ;
하거나 t++ ;
코딩 할 폰션을 검색 할 때 고려됩니다 .
class T
{
// etc.
} ;
T & operator++(T & p_oRight) // ++A
{
// Do increment of p_oRight value
return p_oRight ;
}
T operator++(T & p_oRight, int) // A++
{
T oCopy ;
// Copy p_oRight into oCopy
// Do increment of p_oRight value
return oCopy ;
}
C ++ 관점 (C ++ 컴파일러 관점 포함)에서 이러한 비 멤버 함수는 동일한 네임 스페이스에있는 한 여전히 T 인터페이스의 일부라는 점을 기억하는 것이 중요합니다.
비 멤버 함수 표기법에는 두 가지 잠재적 이점이 있습니다.
- T의 친구로 만들지 않고 코드를 작성하면 T의 캡슐화가 증가합니다.
- 코드를 소유하지 않은 클래스 나 구조체에도 적용 할 수 있습니다. 이것은 선언을 수정하지 않고 객체의 인터페이스를 향상시키는 비 간섭 적 방법입니다.
다음과 같이 선언하십시오.
class A
{
public:
A& operator++(); //Prefix (++a)
A operator++(int); //Postfix (a++)
};
Implement properly - do not mess with what everyone knows they do (increment then use, use then increment).
I know it's late, but I had the same problem and found a simpler solution. Don't get me wrong, this is the same solution as the top one (posted by Martin York). It is just a bit simpler. Just a bit. Here it is:
class Number
{
public:
/*prefix*/
Number& operator++ ()
{
/*Do stuff */
return *this;
}
/*postfix*/
Number& operator++ (int)
{
++(*this); //using the prefix operator from before
return *this;
}
};
The above solution is a bit simpler because it doesn't use a temporary object in the postfix method.
'program tip' 카테고리의 다른 글
자바에서 .mp3 및 .wav를 재생 하시겠습니까? (0) | 2020.08.13 |
---|---|
PHP에서 $$ (달러 또는 더블 달러)는 무엇을 의미합니까? (0) | 2020.08.13 |
Rails 모듈에서 mattr_accessor는 무엇입니까? (0) | 2020.08.13 |
Java에서 따옴표를 이스케이프하지 않고 문자열 리터럴을 작성하는 방법이 있습니까? (0) | 2020.08.13 |
URL이 아닌 IFRAME 소스로서의 HTML 코드 (0) | 2020.08.13 |