原文地址:http://blog.csdn.net/lonfee88/article/details/7462430
1. 封装、继承和this指针
1.1 封装(Encapsulation)
把数据成员声明为private,不允许外界随意存取,只能通过特定的接口来操作,这就是面向对象的
封装特性。
1.2 继承(Inheritance)
子类“暗自(implicit)”具备了父类的所有成员变量和成员函数,
包括private属性的成员(虽然没有访问权限)。
1.3 this指针
矩形类CRect如下:
- class CRect
- {
- private:
- int m_color;
- public:
- void setcolor(int color)
- {
- m_color=color;
- }
- };
有两个CRect对象rect1和rect2,各有各自的m_color成员变量。rect1.setcolor和rect2.setcolor调用的是唯一的CRect::setcolor成员函数,却处理了各自的m_color。
这是因为成员函数是属于类的而不是属于某个对象的,只有一个。成员函数都有一个隐藏参数,名为
this指针,当你调用
- rect1.setcolor(2);
- rect2.setcolor(3);
时,编译器实际上为你做出来的代码是:
2.4 虚析构函数
基类的析构函数一般写成虚函数,这样做是为了当用一个基类的指针删除一个派生类的对象时,派生类的析构函数会被调用。否则会造成内存泄露。
- class ClxBase
- {
- public:
- ClxBase() {};
- virtual ~ClxBase() {};
-
- virtual void DoSomething() { cout << "Do something in class ClxBase!" << endl; };
- };
-
- class ClxDerived : public ClxBase
- {
- public:
- ClxDerived() {};
- ~ClxDerived() { cout << "Output from the destructor of class ClxDerived!" << endl; };
-
- void DoSomething() { cout << "Do something in class ClxDerived!" << endl; };
- };
- ClxBase *pTest = new ClxDerived;
- pTest->DoSomething();
- delete pTest;
输出:
- Do something in class ClxDerived!
- Output from the destructor of class ClxDerived!