标签:纯虚函数 不能 public 使用 转换 派生 引用 资源 des
继承
派生类可访问基类非私有成员,派生类实例也是;
私有继承,也让派生类可访问基类非私有成员,但派生类实例无法访问基类任何成员,并且派生类的的子类也无法访问基类任何成员;
保护继承,与私有继承不同的是,子类的子类是可以访问基类的非私有成员;
注意:仅当必要时才使用私有或保护继承,遇到has-a情况时,尽量用组合或者聚合的方式替代(即将‘基类对象当作‘子类’‘的一个成员属性)
class Motor { public: void SwitchIgnition(); void PumpFuel(); void FireCylinders(); }; class Car { private: Motor heartOfCar; public: void Move() { heartOfCar.FireCylinders(); heartOfCar.PumpFuel(); heartOfCar.SwitchIgnition(); } };
class Platypus:public Mammal,public Reptile,public Bird{};//多继承
多态
将派生类对象视为基类对象,并执行派生类的覆盖函数
class Fish { public: virtual void Swim() { cout << "Fish Swim.." << endl; } }; class Tuna : public Fish { public: virtual void Swim() { cout << "Tuna is fast" << endl; } }; class Carp : public Fish { public: virtual void Swim() { cout << "Carp is slow" << endl; } }; int main() { Tuna t; Carp c; Fish &f1 = t; f1.Swim(); return 0; }
class Fish { public: Fish() { cout <<"Constructed Fish"<< endl; } ~Fish() { cout << "Destroyed Fish" << endl; } }; class Tuna : public Fish { public: Tuna() { cout << "Constructed Tuna" <<endl; } ~Tuna() { cout << "Destroyed Tuna" << endl; } }; void DeleteFishMemory(Fish *pFish) { delete pFish; } int main() { Tuna *pTuna = new Tuna; DeleteFishMemory(pTuna); return 0; } /*输出: **Constructed Fish **Constructed Tuna **Destroyed Fish */
抽象基类与纯虚函数
不能被实例化的基类称为抽象基类,可通过声明纯虚函数创建.
class Fish { public: virtual void Swim() = 0; }; class Tuna : public Fish { public: void Swim() { cout << "Tuna swims fast in the sea " << endl; } };
使用虚继承解决菱形问题,(二义性)
class Animal { public: Animal() { cout << "ANimal constructor" << endl; } int Age; }; class Mammal:public virtual Animal { }; class Bird:public virtual Animal {}; class Reptile:public virtual Animal {}; class Platypus:public Mammal, public Bird, public Reptile { public: Platypus() { cout << "Platypus constructor" <<endl; } }; int main() { Platypus duckBilledp; duckBilledp.Age = 25; return 0; }
从技术上说,C++不支持虚复制构造函数
运算符类型与运算符重载
1, (++)递增运算符
Date operator ++ (){} 单目前缀运算符在类中重载
Date operator ++ (int){}单目后缀运算符在类中重载
2, 转换运算符,下例是用转换运算符将Date转换为const char*
class Date { private: int Day; int Month; int Year; string DateInString; public: Date (int InputDay, int InputMonth, int InputYear) : Day(InputDay), Month(InputMonth), Year(InputYear) {} operator const char*() { ostringstream formattedDate; formattedDate << Day << " / " << Month << " / " << Year; DateInString = formattedDate.str(); return DateInString.c_str(); } }; int main() { Date Holiday (25, 12, 2011); cout << "Holiday is on: " << Holiday << endl; return 0; } //结果:Holiday is on: 25 / 12 / 2011
标签:纯虚函数 不能 public 使用 转换 派生 引用 资源 des
原文地址:http://www.cnblogs.com/qiuxd/p/7086886.html