一 类的指针
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);