roo*_*kie 106 c++ operator-overloading
如何以两种不同的方式为后缀a++和前缀重载operator ++ ++a?
Mar*_*ork 164
应该是这样的:
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.
}
};
Run Code Online (Sandbox Code Playgroud)
sta*_*ica 34
区别在于您为过载选择的签名operator ++.
引自C++常见问题中关于此主题的相关文章(去那里了解更多详情):
Run Code Online (Sandbox Code Playgroud)class Number { public: Number& operator++ (); // prefix ++: no parameter, returns a reference Number operator++ (int); // postfix ++: dummy parameter, returns a value };
PS:当我发现这一点时,我最初看到的只是虚拟参数,但不同的返回类型实际上更有趣; 他们可能会解释为什么++x被认为比x++ 一般更有效.
pae*_*bal 17
您有两种方法可以为类型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 ;
}
} ;
Run Code Online (Sandbox Code Playgroud)
这是另一种方法:只要函数与它们引用的对象位于相同的命名空间中,当编译器搜索要处理++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 ;
}
Run Code Online (Sandbox Code Playgroud)
重要的是要记住,从C++的角度来看(包括C++编译器的观点),那些非成员函数仍然是T接口的一部分(只要它们在同一名称空间中).
非成员函数表示法有两个潜在的优点:
| 归档时间: |
|
| 查看次数: |
83903 次 |
| 最近记录: |