The fundamental ideas behind classes are data abstraction and encapsulation.
-
前置
++
与后置++
从效率上来讲,若是内置数据类型,二者效率相同;但若是非内置数据类型,则前置效率更高,因为前置直接返回修改后自身的引用,而后置则需要将原来的赋值给一个临时变量,修改自身,最后再返回该临时变量。大致如下:Class MyClass{ MyClass& operator ++(); // 前置 MyClass operator ++(int); // 后置,int无实际意义,仅作区分前后置所用 }; MyClass& MyClass::operator ++(){ // Some operations return *this; } const MyClass MyClass::operator ++(int){ MyClass tmp = *this; ++(*this); // 故前置需写在后置前面 return tmp; } // 返回类型的不同与二者的工作逻辑有关
-
Each class defines 0 or more members, which can be either data, functions, or type definitions. All members must be declared inside the class; no way to add members once the class definition is complete.
-
Member functions defined outside the class should add
ClassName::
before the function name, to indicate that they are in the scope of the class. -
Data abstraction is a programming and design technique that relies on the separation of interface and implementation. It should let the programmers using the class understand by the interface but need not to care about how it is implemented concretely.
Encapsulation is a term that describes the technique of combining lower-level elements to form a new, higher-level entity.
-
It’s not always necessary for the class to hide the implementation, sometimes it’s better to expose it. e.g the
pair
type. -
Users of the classes we des