操作符核心示例
++与==操作符
class Vector {
private:
int x;
int y;
public:
int getX() {
return x;
}
int getY() {
return y;
}
Vector operator + (Vector& vector) {
cout << "+运算符重载" << endl;
this->x = this->x + vector.getX();
this->y = this->y + vector.getX();
return Vector(x, y);
}
Vector operator ++ (int) {
cout << "后置++" << endl;
this->x = this->x + 1;
this->y = this->y + 1;
return Vector(x, y);
}
Vector operator ++ () {
cout << "前置++" << endl;
this->x = this->x + 1;
this->y = this->y + 1;
return Vector(x, y);
}
bool operator == (const Vector& v) {
cout << "==运算符重载 "<<this->x << endl;
cout << "==运算符重载 "<<this->y << endl;
cout << "==运算符重载 "<<v.x << endl;
cout << "==运算符重载 "<<v.y << endl;
bool result = this->x == v.x && this->y == v.y;
return result;
}
Vector(int x, int y) {
cout << "普通构造函数" << endl;
this->x = x;
this->y = y;
}
Vector(const Vector& vector) {
cout << "拷贝构造函数" << endl;
this->x = vector.x;
this->y = vector.y;
}
~Vector() {
cout << "析构函数" << endl;
}
friend ostream& operator << (ostream& _Ostr,
const Vector& v) {
cout << v.x << " " << v.y;
return _Ostr;
}
};
void main() {
Vector v1(1, 2);
Vector v2(1, 2);
Vector v = v1 + v2;
v++;
cout << (v1 == v2) << endl;
++v;
cout << v.getX() << " " << v.getY() << endl;
cout << v << endl;
getchar();
}
运行结果
普通构造函数
普通构造函数
+运算符重载
普通构造函数
后置++
普通构造函数
析构函数
==运算符重载 2
==运算符重载 3
==运算符重载 1
==运算符重载 2
0
前置++
普通构造函数
析构函数
4 5
4 5
[]操作符
class Array
{
public:
Array(int size) {
this->size = size;
this->array = (int *)malloc(sizeof(int)*size);
}
~Array() {
if (this->array)
{
free(this->array);
this->array = NULL;
}
}
int& operator [](int index)
{
return this->array[index];
//return *(array + index);
}
void set(int index,int value)
{
this->array[index] = value;
//*(array + index) = value;
}
void printArray()
{
for (int i = 0; i < size; i++)
{
//cout<<array[i]<<endl;
cout<<*(array+i)<<endl;
}
}
private:
int size;
int* array;
};
void main() {
Array *arr = new Array(6);
arr->set(0,8);
arr->set(1,9);
arr->set(2,10);
(*arr)[3] = 11;
(*arr)[4] = 12;
(*arr)[5] = 13;
arr->printArray();
delete(arr);
getchar();
}
运行结果
8
9
10
11
12
13