C++学习笔记一类的构造和析购函数
1. Constructors cannot return values, even if they have return statements. Specifying a constructor with a return type is an error, as is taking the address of a constructor.
构造函数不能返回类型,即使只有return声明语句也不行。指定一个构造函数的返回类型或它的地址都是错误的。
试了一下,效果这样:
class A
{
public:
A ();
};
A::A()
{
return ; //ok, equal to exit;no return type.
return void; //error
return 0; //error
}
2. If a class has a constructor, each object of that type is initialized with the constructor prior to use in a program.
如果类有一个构造器,那么这个类的每个对象都应该在程序使用前先初始化构造函数。
Constructors are called at the point an object is created. Objects are created as:
Global (file-scoped or externally linked) objects.
Local objects, within a function or smaller enclosing block.
Dynamic objects, using the new operator. The new operator allocates an object on the program heap or “free store.”Temporary objects created by explicitly calling a constructor.
Temporary objects created implicitly by the compiler.
Data members of another class. Creating objects of class type, where the class type is composed of other class-type variables, causes each object in the class to be created.
Base class subobject of a class. Creating objects of derived class type causes the base class components to be created.
构造函数在对象生成时调用,以下情况下生成对象:
全局对象;局部对象;用new在堆上动态生成的对象;外部显式调用生成的临时对象;编译器隐式调用生成的临时对象;作为另一个类的数据成员;另一个类的基类。
3. The default method of initialization is to perform a bit-for-bit copy from the initializer into the object to be initialized. This technique is applicable only to:
Objects of built-in types. For example: int i = 100;
Pointers. For example: int i ; int *pi = &i;
References. For example: String sFileName("FILE.DAT"); String &rs = sFileName;
Objects of class type, where the class has no private or protected members, no virtual functions, and no base classes. For example:struct Point{ int x,y;}; Point pt = (10, 20); //static storage class only
缺省初始化方法是执行位拷贝。只适用于:内建类型;指针;引用;没有私有成员或保护成员,没有虚函数,并且没有基类的类对象。
什么情况下需要对类定义自拷贝函数和重载赋值函数?
答:当成员变量不允许bitwise的情况下,需要 memberwis。比如string, list, vetor等。
什么情况下析构函数应该声明为虚函数?
答:当类用作基类时,析构函数必须定义为虚函数。否则,派生类对象无法调用自身的析构函数。
浙公网安备 33010602011771号