6: Initialization and Cleanup

来源:互联网 发布:图像形态学 知乎 编辑:程序博客网 时间:2024/06/13 00:51

1.constructor

In C++, the class designer can guarantee initialization of every object by providing a special function called the constructor whose name is the same as class's name.

class A{private:int a;public:A();};int main(){A ta;}
In this simple example, storage is allocated for the object. And the compiler quietly inserts the call to A::A() for the object a at the point of definition. Like any member function, the first(secret) argument to the constructor is the this pointer - the address of the object for which it is being called.

Notice: If you have a constructor, the compiler ensures that construction always happend. If there are no constructors for a class, the compiler will automatically create one for you.

2.destructor

The destructor never has any arguments because destruction never needs any options.

3.no return value

Both the constructor and destructor are very unusual types of functions: they have no return value. This is distinctly diffenent from a void return value, in which the function returns nothing but you still have the option to make it something else.

原创粉丝点击