构造函数
2016-03-02 17:28
405 查看
1、类内部没有任何构造函数时
2、类内部有无参数的构造函数
3、类内部有多个构造函数时
执行结果:
执行结果:
此时,说明如果类内部有构造函数,那么在调用构造函数时,编译器就会去匹配类内部构造函数,看是否可以匹配上。
此程序,若添加无参构造函数则可以正确运行;或者将构造函数改为stu(int a=1,string b=”jack”)。
4、构造函数用在数组中
NOTE:
构造函数并不负责分配对象的存储空间,只是在对象创建之后,即存储空间分配之后,对对象的属性值进行初始化。
class stu{ private : int id; string name; public: }; int main() { stu b; return 0; }
此时,调用编译器调用默认的无参构造函数,此构造函数什么也不做。
2、类内部有无参数的构造函数
class stu{ private : int id; string name; public: stu() { id=1; name="jack"; cout<<"this construc function is used"<<endl; } void show() { cout<<id<<" "<<name<<endl; } }; int main() { stu b; b.show(); return 0; }
此时调用类内部的无参数构造函数
3、类内部有多个构造函数时
class stu{ private : int id; string name; public: stu(int a,string b="jack") { id=a; name=b; cout<<"finish"<<endl; } stu() { id=1; name="jack"; cout<<"this construct function is used"<<endl; } void show() { cout<<id<<" "<<name<<endl; } }; int main() { stu a(1); a.show(); stu b; b.show(); return 0; }
执行结果:
1 jack this construct function is used 1 jack
class stu{ private : int id; string name; public: stu(int a,string b="jack") { id=a; name=b; cout<<"finish"<<endl; } void show() { cout<<id<<" "<<name<<endl; } }; int main() { stu b; b.show(); return 0; }
执行结果:
[Error] no matching function for call to 'stu::stu()'
此时,说明如果类内部有构造函数,那么在调用构造函数时,编译器就会去匹配类内部构造函数,看是否可以匹配上。
此程序,若添加无参构造函数则可以正确运行;或者将构造函数改为stu(int a=1,string b=”jack”)。
4、构造函数用在数组中
class test{ test(int n,int m){}//1 test(int n){}//2 test(){}//3 };
test array1[3]={1,test(1,2)}; 第一个对象初始化调用构造函数1,第二对象初始化调用构造函数2,第三个对象初始化调用无参构造函数3;
test array2[3]={test(1,2),test(1,2),1}; //test array2[3],生成三个test对象,三个元素分别用2,2,1初始化
test * pArray[3]={new test(4),new test(1,2)} pArray是指针数组,每一元素都是指向test对象的指针; test * pArray[3]前半句并不会生成test对象,只是构建了三个指针。 第一个指针指向了new test(4)生成的对象,第二个指针指向new test(1,2)生成的对象,第三个指针为空。
NOTE:
构造函数并不负责分配对象的存储空间,只是在对象创建之后,即存储空间分配之后,对对象的属性值进行初始化。
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- 部分喷墨机初始化方法
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- C#中数组初始化与数组元素复制的方法
- 详解C#编程中构造函数的使用
- C#中结构(struct)的部分初始化和完全初始化实例分析
- C++联合体转换成C#结构的实现方法
- C++高级程序员成长之路
- C++编写简单的打靶游戏
- C++ 自定义控件的移植问题
- C++变位词问题分析
- C/C++数据对齐详细解析
- C++基于栈实现铁轨问题
- C++中引用的使用总结
- 使用Lua来扩展C++程序的方法