1.繼承類型
繼承形式如下:
class derived-class: access-specifier base-class
當一個類派生自基類,該基類可以被繼承為 public、protected 或 private 幾種類型。繼承類型是通過上面講解的通路修飾符 access-specifier 來指定的。
我們幾乎不使用 protected 或 private 繼承,通常使用 public 繼承。當使用不同類型的繼承時,遵循以下幾個規則:
公有繼承(public):當一個類派生自公有基類時,基類的公有成員也是派生類的公有成員,基類的保護成員也是派生類的保護成員,基類的私有成員不能直接被派生類通路,但是可以通過調用基類的公有和保護成員來通路。
保護繼承(protected): 當一個類派生自保護基類時,基類的公有和保護成員将成為派生類的保護成員。
私有繼承(private):當一個類派生自私有基類時,基類的公有和保護成員将成為派生類的私有成員。
2.虛繼承
http://blog.csdn.net/iloveyousunna/article/details/78535618
3.運算符重載
大部分的重載運算符可被定義為普通的非成員函數或者被定義為類成員函數。
#include <iostream>
using namespace std;
class Box{
public:
int height;
int width;
Box(int height, int width) : height(height), width(width){}
//Box operator+(const Box& box);
};
Box operator+(const Box b1, const Box b2){
return Box(b1.height + b2.height, b1.width + b2.width);
}
//Box Box::operator+(const Box& box){
// return Box(this -> height + box.height, this -> width + box.width);
//}
int main(){
Box b1(12,34);
Box b2(12,32);
Box b3 = b1 + b2;
cout << b3.height << endl;
cout << b3.width << endl;
return 0;
}
4.多态
多态主要是通過virtual實作的,如果基類中不加virtual,這就是所謂的靜态多态,或靜态連結,函數調用在程式執行前就準備好了,有時候這也被成為早綁定。如果加上virtual,會告訴編譯器不要靜态連結到該函數,我們想要的是在程式中任意點可以根據所調用的對象類型來選擇調用的函數,這種操作被成為動态連結,或後期綁定。
#include <iostream>
using namespace std;
class Shape{
protected:
int width,height;
public:
Shape(int a=0, int b=0){
width = a;
height = b;
}
int area(){
cout << "Parent class area" <<endl;
return 0;
}
};
class Rectangle: public Shape{
public:
Rectangle(int a=0, int b=0):Shape(a, b){}
int area(){
cout << "Rectangle class area" << endl;
return (width * height);
}
};
class Triangle: public Shape{
public:
Triangle(int a=0, int b=0):Shape(a,b){}
int area(){
cout << "Triangle class area" << endl;
return (width * height / 2);
}
};
int main(){
Shape *shape;
Rectangle rec(10, 7);
Triangle tri(10, 5);
shape = &rec;
shape -> area();
shape = &tri;
shape -> area();
return 0;
}
輸出結果:
Parent class area
Parent class area
如果加上virtual:
#include <iostream>
using namespace std;
class Shape{
protected:
int width,height;
public:
Shape(int a=0, int b=0){
width = a;
height = b;
}
virtual int area() = 0;
};
class Rectangle: public Shape{
public:
Rectangle(int a=0, int b=0):Shape(a, b){}
int area(){
cout << "Rectangle class area" << endl;
return (width * height);
}
};
class Triangle: public Shape{
public:
Triangle(int a=0, int b=0):Shape(a,b){}
int area(){
cout << "Triangle class area" << endl;
return (width * height / 2);
}
};
int main(){
Shape *shape;
Rectangle rec(10, 7);
Triangle tri(10, 5);
shape = &rec;
shape -> area();
shape = &tri;
shape -> area();
return 0;
}
輸出結果:
Rectangle class area
Triangle class area
當然這裡不一定是純虛函數,加上virtual就行,父類也可以有自己的實作。
5.純虛函數
當你在基類中不能對虛函數給出有意義的實作,這個時候就會用到純虛函數。=0告訴編譯器,函數沒有主體,上面的虛函數是純虛函數。
如果有一個或者以上的純虛函數,那麼這個類就是抽象類,不能有自己的執行個體。