Guaranteed initialization with the constructor
◆ If a class has a constructor, the compiler automatically calls that constructor at the point an object is created, before client programmers can get their hands on the object.
◆ The name of the constructor is the same as the name of the class.
How a constructor does?
class X { private: int i; public: X(); //构造函数,不能有任何返回值、参数,名称必须和类的名称完全一样(包括大小写) };【例】
#include <iostream> using namespace std; class X { private: int i; public: X(); void f(); }; X::X() { i = 0; printf("X::X()-- this = %p\n", this); } void X::f() { this->i = 20; printf("X::f() -- this = %p\n", this); printf("X::f() -- &i = %p\n", &i); } int main(int argc, const char* argv[]) { X x; x.f(); }我们能看到,一旦定义了类X的一个对象x,就会执行构造函数X::X(),程序的运行结果如下图所示:
Constructors with arguments
◆ The constructor can have arguments to allow you to specify how an object is created, give it initialization values, and so on.
Tree(int i){...} Tree t(12);【例】
#include <iostream> using namespace std; class Tree { private: int height; public: Tree(int initialHeight); void print(); }; Tree::Tree(int initialHeight) { height = initialHeight; cout << "inside Tree Constructor" << endl; } void Tree::print() { cout << "The height is " << height << endl; } int main(int argc, const char* argv[]) { cout << "before opening brace" << endl; { Tree t(12); //构造函数被调用,且被传入参数的情况 cout << "after Tree t creation" << endl; t.print(); } cout << "after closing brace" << endl; return 0; }这样,我们可以很清楚地看到构造函数调用的时刻、构造函数带有参数时是如何被调用的:
The destructor
◆ In C++, clean up is as important as initialization and is therefore guaranteed with the destructor.
◆ The destructor is named after the name of the class with a leading tilde (~). The destructor never has any arguments.
class Y { public: ~Y(); //析构函数没有类型、没有参数 };【例】
#include <iostream> using namespace std; class Tree //类Tree的声明 { private: int height; public: Tree(int initialHeight); //构造函数的声明 ~Tree(); //析构函数的声明 void print(); }; Tree::Tree(int initialHeight) //构造函数的定义 { height = initialHeight; cout << "inside Tree Constructor" << endl; } Tree::~Tree() //析构函数的定义 { cout << "inside Tree Destructor" << endl; print(); } void Tree::print() { cout << "The height is " << height << endl; } int main(int argc, const char* argv[]) { cout << "before opening brace" << endl; { Tree t(12); cout << "after Tree t creation" << endl; t.print(); } cout << "after closing brace" << endl; return 0; }When is a destructor called?
◆ The destructor is called automatically by the compiler when the object goes out of scope.
◆ The only evidence for a destructor call is the closing brace of the scope that surrounds the object.
