第十讲 拷贝构造函数
int a=0;
int b=a;
CStudent stud1("TOM",20);
CStudent stu2(stu1);
构造方法初始化
利用构造好的stud1来初始化stud2
叫做拷贝构造方法
#include <iostream.h>
main()
{
CStudent stud1("TOM",20);
CStudent stu2(stu1);
}
class CStudent
{
public:
CStudent(char *name, int score);
CStudent(const CStudent &stu);
private:
char *m_name;
int m_score;
};
CStudent::CStudent(char *name,int score)
{
m_name=name;
m_scor=score;
}
CStudent::CStudent(const CStudent &stu)
{
strcpy(m_name,stu.m_name);
m_age=stu.m_age;
}
stu是stu1的引用 ,是stu1的别名,对stu的操作就是对stu1的操作
两个构造依法 构造方法的重载
构造函数没有返回值,只有一个参数,因为是拷贝,
前面构造好了,只是拷贝。
原理,还不是很清楚。
注意点:const的作用是不充许stu在这个函数中被改变,
不能和值传递,只能用引用传递
第十二讲 实验——上
目的
学习定义一类
学习创建一个对象
学习使用一个对象
环境VC6.0
创建类,用户只能操作接口,是公有的
数据是私有的,
#include <iostream.h>
#include <string.h>//strcpy head file
class CStudent
{
public:
CStudent(); //构造函数一定和它的类名字是一样的
CStudent(char *name,int age); //可以和成员变量区分开来
void initialize(char *name,int age); //赋值
void output(); //输出类对象
private:
char m_name[20];
int m_age;
};
//习惯在成员变量前面加上m_表示成员变量,以区分
//实现
CStudent::CStudent() //类很多,要用域操作符表明属于哪一个类
{
strcpy(m_name,"");
m_age = 0;
} //构造函数就是对数据成员进行初始化
CStudent::CStudent(char *name,int age)
{
strcpy(m_name,name);
m_age = age; //从形参传递过来
} //实现两个构造函数
void CStudent::initialize(char *name,int age)
{ strcpy(m_name,name);
m_age = age;
}
void CStudetn::output()
{
cout<<m_name<<" "<<m_age<<endl;
}
//定义对象
void main()
{
CStudent stu1;//定义对象
stu1.output();//访问对象的公开成员
//中间隐含了构造的使用
CStudent stu2("Tom",23);
stu2.output();
}
第十三讲 实验——下
目的
掌握对象数组的创建
掌握对象指针的使用
#include <iostream.h>
#include <string.h>//strcpy head file
class CStudent
{
public:
CStudent(); //构造函数一定和它的类名字是一样的
CStudent(char *name,int age); //可以和成员变量区分开来
void initialize(char *name,int age); //赋值
void output(); //输出类对象
private:
char m_name[20];
int m_age;
};
//习惯在成员变量前面加上m_表示成员变量,以区分
//实现
CStudent::CStudent() //类很多,要用域操作符表明属于哪一个类
{
strcpy(m_name,"");
m_age = 0;
} //构造函数就是对数据成员进行初始化
CStudent::CStudent(char *name,int age)
{
strcpy(m_name,name);
m_age = age; //从形参传递过来
} //实现两个构造函数
void CStudent::initialize(char *name,int age)
{ strcpy(m_name,name);
m_age = age;
}
void CStudent::output()
{
cout<<m_name<<" "<<m_age<<endl;
}
//定义对象
void main()
{
//无参的调用
/* CStudent stu1;
stu1.output();
CStudent stu2("Tom",23);
stu2.output();
stu2.initialize("JIM",44);
stu2.output();
*/
//数组的使用和初始化
/* CStudent stu[3];
CStudent stu[3]={
CStudent(),CStudent("Crystal",21),CStudent()
};
for(int i=0;i<3;i++)
{
stu[i].output();
}
*/
//指针的使用和初始化
CStudent stu;
CStudent *p = &stu;
p->output();
(*p).output();
}