C++类的指针和操作符重载

一 类的指针

1 代码

#include <iostream>
using namespace std;
class CRectangle {
    int width, height;
public:
    void set_values(int,int);
    int area(void) {return (width*height);}
};
  
void CRectangle::set_values(int a, int b) {
    width = a;
    height = b;
}
    
int main() {
    CRectangle a,*b,*c;
    CRectangle *d = new CRectangle[2];
    b = new CRectangle;
    c = &a;
    a.set_values(1,2);
    b->set_values(3,4);
    d->set_values(5,6);
    d[1].set_values(7,8);
    cout << "a area: " << a.area() << endl;
    cout << "*b area: " << b->area() << endl;
    cout << "*c area: " << c->area() << endl;
    cout << "d[0] area: " << d[0].area() << endl;
    cout << "d[1] area: " << d[1].area() << endl;
    return 0;
}

2 运行

[root@localhost test]# g++ test.cpp -g -o test
[root@localhost test]# ./test
a area: 2
*b area: 12
*c area: 2
d[0] area: 30
d[1] area: 56

3 说明

要想直接引用一个由指针指向的对象中的成员,需要使用操作符->。

二 操作符重载的例子

1 代码

#include <iostream>
using namespace std;
   
class CVector {
public:
    int x, y;
    CVector() {}
    ;
    CVector(int, int);
    CVector operator +(CVector);
};
    
CVector::CVector(int a, int b) {
    x = a;
    y = b;
}
    
CVector CVector::operator+(CVector param) {
    CVector temp;
    temp.x = x + param.x;
    temp.y = y + param.y;
    return (temp);
}
    
int main() {
    CVector a(3, 1);
    CVector b(1, 2);
    CVector c;
    //c = a + b;
    c = a.operator+(b);
    cout << c.x << "," << c.y<<endl;
    return 0;
}

2 运行

[root@localhost test]# g++ test.cpp -g -o test
[root@localhost test]# ./test
4,3

3 说明

操作符合重载可以用下面两种方式进行调用:

c = a + b;

c = a.operator+(b);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值