栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++重载的例子

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++重载的例子

此处代码,请思考理解
  • 重载运算符,为什么需要返回引用?
  • 什么是委托构造函数?
  • 什么是类内重载,什么是类外重载?默认调用那个?
  • 数组对象
  • 函数对象(仿函数)
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;

class Point {
public:
    Point();
    Point(int x, int y);
    //类内重载
    Point operator+(const Point &);
    Point &operator+=(int);
    int operator[](string);
    int getX() {return x; }
    int getY() {return y; }

private:
    friend Point operator+(const Point &, const Point &);
    friend ostream &operator<<(ostream &, const Point &);
    int x, y;
};

class PPoint {
public:
    PPoint(Point *p) : p(p) {}
    Point *operator->() {return p;}
private:
    Point *p;
};

class ADD {
public:
    ADD(int c) : c(c) {}
    int operator()(int a, int b) {
        return a + b + c;
    } 
private:
    int c;
};

//委托构造函数
Point::Point() : Point(0, 0) {}
Point::Point(int x, int y) : x(x), y(y) {}
//数组对象
int Point::operator[](string s) {
    if (s == "x") return x;
    if (s == "y") return y;
    return 0;
}

ostream &operator<<(ostream &out, const Point &a) {
    out << "(" << a.x << "," << a.y << ")";
    return out;
}

Point &Point::operator+=(int n){
    x += n, y += n;
    return *this;
}
//类内重载
Point Point::operator+(const Point &a) {
    cout << "inner operator+" << endl;
    Point c(x + a.x, y + a.y);
    return c;
}
//类外重载
Point operator+(const Point &a, const Point &b) {
    cout << "outer operator+" << endl;
    Point c(a.x + b.x, a.y + b.y);
    return c;
}

int main() {
    ADD add(5);//仿函数,可调用对象
    cout << add(6, 7) << endl;
    Point a(3, 4);
    Point b(7, 9);
    cout << a["x"] << endl;//数组对象
    cout << a["y"] << endl;
    Point c = a + b;
    cout << a << endl;
    cout << b << endl;
    cout << c << endl;
    (a += 3) += 2;//x和y统一加上3,再加上2
    cout << a << endl;

    PPoint p = &a;
    cout << p->getX() << " " << p->getY() << endl;
    return 0;
}

输出
18
3
4
inner operator+
(3,4)
(7,9)
(10,13)
(8,9)
8 9
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/396024.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号