标签:
构造函数
可以初始化内部成员
可以带参数
最重要的作用是可以创建对象本身
C++规定,每个类必须有一个构造函数,没有构造函数就不能创建任何对象(实例)
如果一个类没有任何的构造函数,C++编译器会提供一个没有参数的构造函数,只负责创建对象,不做任何初始化工作
例:
//--无构造函数-------------------------------------------------------- #include <iostream.h> class Point { public: int x; int y; void output() { cout<<x<<endl<<y<<endl; } }; void main() { Point pt; pt.output(); //无构造函数时由于未对x,y初始化,输出意外值。若创建初始化函数也有忘记调用的可能性 } //--有构造函数-------------------------------------------------------- #include <iostream.h> class Point { public: int x; int y; Point() //# 构造函数没有返回值,并且名称使用类名 { x=0; y=0; } void output() { cout<<x<<endl<<y<<endl; } }; void main() { Point pt; //程序执行到此处会跳转到构造函数处(#号处)进行初始化 pt.output(); //加入构造函数后,会自动进行初始化,不需要认为干预 }
标签:
原文地址:http://www.cnblogs.com/ROHALLOWAY/p/4562183.html