我们可以为增量前和增量后重载operator++吗?例如,调用SampleObject++和++SampleObject会给出正确的结果。
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; */
} */
};我们不能仅仅基于返回类型来重载一个函数,而且即使我们认为它是允许的,它也不能解决问题,因为重载解析中的歧义。
既然提供了操作符重载,以使内置类型的行为像用户定义的类型,为什么我们不能同时使用我们自己的类型的前增量和后增量?
发布于 2013-03-06 18:02:44
增量运算符的后缀版本接受一个伪int参数,以消除歧义:
// prefix
CSample& operator++()
{
// implement increment logic on this instance, return reference to it.
return *this;
}
// postfix
CSample operator++(int)
{
CSample tmp(*this);
operator++(); // prefix-increment this instance
return tmp; // return value before increment
}发布于 2013-03-06 20:29:10
类型T的前增量和后增量的标准模式
T& T::operator++() // pre-increment, return *this by reference
{
// perform operation
return *this;
}
T T::operator++(int) // post-increment, return unmodified copy by value
{
T copy(*this);
++(*this); // or operator++();
return copy;
}(您也可以调用一个公共函数来执行递增,或者如果它是一个简单的一行程序,比如成员上的++,那么只需在这两个函数中都执行)
发布于 2013-03-06 18:06:06
为什么我们不能对我们自己的类型同时使用前增量和后增量。
您可以:
class CSample {
public:
int m_iValue;
CSample() : m_iValue(0) {}
CSample(int val) : m_iValue(val) {}
// Overloading ++ for Pre-Increment
int /*CSample& */ operator++() {
++m_iValue;
return m_iValue;
}
// Overloading ++ for Post-Increment
int operator++(int) {
int value = m_iValue;
++m_iValue;
return value;
}
};
#include <iostream>
int main()
{
CSample s;
int i = ++s;
std::cout << i << std::endl; // Prints 1
int j = s++;
std::cout << j << std::endl; // Prints 1
}https://stackoverflow.com/questions/15244094
复制相似问题