Can we overload operator++
for pre-increment and post-increment? i.e. calling SampleObject++
and ++SampleObject
results correctly.
class CSample {
public:
int m_iValue; // just to directly fetch inside main()
CSample() : m_iValue(0) {}
CSample(int val) : m_iValue(val) {}
// Overloading ++ for Pre-Increment
int /*CSample& */ operator++() { // can also adopt to return CSample&
++(*this).m_iValue;
return m_iValue; /*(*this); */
}
// Overloading ++ for Post-Increment
/* int operator++() {
CSample temp = *this;
++(*this).m_iValue;
return temp.m_iValue; /* temp; */
} */
};
We can't overload a function based only on return type, and also even if we take it as permitted, it doesn't solve the problem because of the ambiguity in call resolution.
Since operator overloading is provided to make built-in types behave like as user-defined types, why we can't avail both pre and post increment for our own types at the same time.
Question&Answers:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…