C++要点笔记(24)——类的静态成员

C++类中的静态数据成员(static data member)只是声明(declaration),不是定义(definition),需要在类定义外显示地进行定义。这样做是避免定义类的头文件被多个文件包含后,引起编译问题:

class A {
public:
    static int a;
};

int A::a;

除了静态数据成员(static data member),还有静态成员函数(static member function)。它们的共同点是属于整个类,而不属于类的某一个实例,可以通过“类名::成员”方式来访问。需要注意的是,由于静态成员函数没有指向实例的this指针,所以它只能访问类的静态数据成员,而不能访问每个实例的成员。

参考资料:
Static Data Member Initialization
Static data members in C++

 

C++要点笔记(22)——多态(Polymorphism)

下面是对Polymorphism的解释:

Polymorphism means “many forms”. It is where one type of thing comes in many forms. So you can treat it according to its type, but it will behave differently according to which form of that type it happens to be.

Polymorphism含义为一个类型有多种形式:这些形式虽属于同一类型,但是具体的行为不同。

Polymorphism stems from inheritance. The whole idea is that you have a general base class and more specific derived classes. You can then write code that works with the base class… and polymorphims makes your code not only work with the base class, but all derived classes.

Polymorphism源于继承,它可以让代码对基类和衍生类都能工作。

One of the features of derived classes is that a pointer to a derived class is type-compatible with a pointer to its base class. Polymorphism takes advantage of this feature.

Polymorphism利用了衍生类的指针与基类指针兼容的特性。

A class that declares or inherits a virtual function is called a polymorphic class.

Polymorphism class是定义或继承了virtual functionclass

Pure virtual function定义:

virtual void f() = 0;

包含pure virtual function定义的类是abstract class

参考资料:
I don’t understand Polymorphism at all?
C++ polymorphism and abstract base class

 

C++要点笔记(21)——引用(reference)

Reference可以看做是一个变量的别名:

int x;
int& foo = x;

Reference的一个重要用途是用在函数传参中:

int workWithClass( const MyClass& a_class_object )
{
}

在上述函数中,因为参数是引用,所以省去了copy参数的工作;并且由于有const修饰,所以不会对参数所指向的对象进行修改。

一旦reference绑定了一个object,它不能再绑定其它的object(参考stackoverflow)。

参考资料:
C++ References