首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何区分C++中两个相似的操作符重载

如何区分C++中两个相似的操作符重载
EN

Stack Overflow用户
提问于 2020-08-03 02:46:48
回答 1查看 49关注 0票数 0

我有这段C++代码来重载增量前后的操作符。这些方法之间唯一的区别是它们的参数数目。

我想知道C++如何理解在运行y=++x和z=x++命令时应该调用哪个方法(增量前还是增量后)。

代码语言:javascript
复制
class location {
 
    private:  int longitude, latitude;
 
    public:
        location(int lg = 0, int lt = 0) { longitude = lg; latitude = lt; }
 
        void show() { cout << longitude << "," << latitude << endl; }
 
        location operator++();     // pre-increment
        location operator++(int);  // post-increment
};
 
// pre-increment
location location::operator++() {  // z = ++x;
 
    longitude++;
    latitude++;
    return *this;
}
 
// post-increment
location location::operator++(int) {  // z = x++;
 
    location temp = *this;
    longitude++;
    latitude++;
    return temp;
}
 
int main() {
 
    location x(10, 20), y, z;
    cout << "x = ";
    x.show();
    ++x;
    cout << "(++x) -> x = ";
    x.show();
 
    y = ++x;
    cout << "(y = ++x) -> y = ";
    y.show();
    cout << "(y = ++x) -> x = ";
    x.show();
 
    z = x++;
    cout << "(z = x++) -> z = ";
    z.show();
    cout << "(z = x++) -> x = ";
    x.show();
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-08-03 02:56:36

本质上,忽略++重载中的参数会告诉c++您正在创建前缀重载。

包括参数告诉c++您正在重载后缀操作符。因此,当您运行++x时,它将运行前缀,而x++将运行后缀。

此外,我还可以补充一下,参数中的int不是整数数据类型。

如果您想要更多的理解,那么这里就是我找到信息的地方:https://www.programiz.com/cpp-programming/increment-decrement-operator-overloading

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63223074

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档