运算符重载:
可重载运算符:
+ - * / % ^
& | ~ ! , =
< > <= >= ++ --
<< >> == != && ||
+= -= /= %= ^= &=
|= *= <<= >>= [] ()
-> ->* new new[] delete delete[]
不可重载运算符:
:: .* . ?:
运算符重载的示例:
一元运算符重载:
class Point{
private:
int x;
int y;
public:
Point(int X,int Y):x(X),y(Y) { }
void print() {printf("%d %d\r\n", x, y); }
Point operator- ()
{
return Point(-x, -y);
}
// 前置++
Point operator++()
{
x++;
y++;
returnPoint(x,y);
}
// 后置++
Point operator++(int)
{
int tempX = x;
int tempY = y;
x++;
y++;
returnPoint(tempX, tempY);
}
};
继续上面的例子,重载二元运算符:
Point operator +(const Point& b)
{
returnPoint(x+b.x, y+b.y);
}
继续上面的例子,重载关系运算符:
bool operator >(const Point&b)
{
return x*y >b.x*b.y;
}
继续上面的例子,重载输入输出流:
friend ostream &operator<<(ostream &output, const Point &p)
{
output <<"X: " << p.x << " Y: " << p.y <<endl;
return output;
}
friend istream &operator>>(istream &input, Point &p)
{
char sx[100];
char sy[100];
input >>sx >> sy;
p.x = atoi(sx);
p.y = atoi(sy);
return input;
}
继续上面的例子,重载赋值运算符:
void operator=(const Point& b)
{
x = b.x;
y = b.y;
}
继续上面的例子,重载小括号:
Point operator ()(int xx, int yy)
{
returnPoint(x*xx, y*yy);
}
重载中括号:
class SafeArr{
private:
int arr[100];
public:
int&operator [](int i)
{
return (i <100 && i > -1) ? arr[i] : arr[0];
}
};
重载成员访问运算符:
class Demo{
private:
int data;
public:
Demo() { }
Demo(intd):data(d) { }
voidprintdata() { cout << data << endl; }
};
class DemoList{
private:
vector<Demo*>arr;
int index;
public:
DemoList()
{
index = 0;
}
voidadd(Demo& d) { arr.push_back(&d); }
voidoperator++() { index = ++index % arr.size(); }
voidoperator++(int) { operator++(); }
Demo* operator->() const { return arr[index]; }
};
Demo ds[30];
for (int i = 0; i < 30; i++)
{
ds[i] =Demo(i);
}
DemoList dl = DemoList();
for (int i = 0; i < 30; i++)
{
dl.add(ds[i]);
}
for (int i = 0; i < 40; i++)
{
dl->printdata();
dl++;
}
多态:
虚函数:虚函数是在基类中使用关键字 virtual 声明的函数。在派生类中重新定义基类中定义的虚函数时,会告诉编译器不要静态链接到该函数。想要在程序中任意点可以根据所调用的对象类型来选择调用的函数,这种操作被称为动态链接,或后期绑定。
纯虚函数:在基类中定义的虚函数,该虚函数没有实现,这种虚函数为纯虚函数。
使用虚函数实现多态:
class Shape{
protected:
int area;
public:
virtual voidshowArea() { cout << area << endl; }
};
class Rectangle:public Shape{
private:
int height,width;
public:
Rectangle(inth, int w):height(h), width(w) { }
void showArea(){ area = height*width; cout << "Rectangle area : " <<area << endl; }
};
class Triangle:public Shape{
private:
int height,bottom;
public:
Triangle(int h,int b):height(h), bottom(b) { }
void showArea(){ area = height*bottom/2; cout << "Triangle area : " <<area << endl; }
};
Shape* s;
s = &(Rectangle(10, 20));
s->showArea();
s = &(Triangle(10, 20));
s->showArea();
纯虚函数举例(接口):
virtual void showArea() =0;