赞
踩
3月中旬参加宣讲会,做了X软公司的C++笔试题,里面有一道“默认拷贝构造函数的题”,由于好久没复习C++基础知识,当时连基本的概念都想不来了了。于是乎,开始拿起以前看的谭浩强C++复习起来,现在书快要要啃完了,觉得收获颇多。好比练武功,秘籍虽然重要,但更重要的还是深厚的内力和扎实的基本功。
C++中的构造函数可以分为4类:
(1)默认构造函数。以Student类为例,默认构造函数的原型为
Student();//没有参数
(2)初始化构造函数
Student(int num,int age);//有参数
(3)复制(拷贝)构造函数
Student(Student&);//形参是本类对象的引用
(4)转换构造函数
Student(int r) ;//形参时其他类型变量,且只有一个形参
默认构造函数和初始化构造函数在定义类的对象的时候,完成对象的初始化工作。
class Student { public: //默认构造函数 Student() { num=1001; age=18; } //初始化构造函数 Student(int n,int a):num(n),age(a){} private: int num; int age; }; int main() { //用默认构造函数初始化对象S1 Student s1; //用初始化构造函数初始化对象S2 Student s2(1002,18); return 0; }
Student s2(1002,1008);
Student s3(s2);//将对象s2复制给s3。注意复制和赋值的概念不同。
Student s4;
s4=s2;//这种情况叫做赋值,自己体会吧
Student(Student &b)
{
this.x=b.x;
this.y=b.y;
}
Student(int r)
{
int num=1004;
int age= r;
}
Student s1(01,18);
Student s2(02,20);
s1+s2; //其值就是s1.age + s2.age = 18+20=36。
####相关系列
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。