第二十六讲 静态成员函数
定义:直接可以由类直接引用的函数,叫做静态成员函数;
格式
static 函数类型 函数名;
实现的时候 不用static
在此应注意,不可用this指针了
因为this指针只是指明当前的对象,而此时用静态函数时,对象不明。会
出错
第二十七讲 静态成员函数实验
掌握静态成员函数的使用
第二十八讲 函数的重载
定义:同名但是不同参数或者参数的个数的函数叫做函数的重载
例如:
void input();
void input(char *name,int age);
void input(CStudent student);
个数相同,类型不同,也是重载
除了成员函数,普通函数,友元函数,都是可以重载的
函数的重载的作用
能够根据一个函数参数的类型或个数来调用相同函数名的函数
有很多函数的时候,要记,要查的太多了,函数名相同时,只要记几个
就行了,用时,用参数或类型来调用对应函数就可以了;
第二十九讲 实验
成员函数重载
普通函数重载
友元函数重载
#include <iostream.h>
#include <string.h>//strcpy head file
class CStudent
{
public:
CStudent(); //构造函数一定和它的类名字是一样的
CStudent(char *name,int age); //可以和成员变量区分开来
CStudent(const CStudent &student);//拷贝构造函数
//~CStudent();
//friend CStudent &input(CStudent &student,char *name,
int age);
friend void initialize(CStudent &student);
friend void initialize(CStudent &student,char *name,int
age);
// void initialize(char *name,int age); //赋值
void output(); //输出类对象
private:
//char m_name[20];
//int m_age;
char name[20];
int age;
};
//int CStudent::age = 0;
//习惯在成员变量前面加上m_表示成员变量,以区分
//实现
CStudent::CStudent() //类很多,要用域操作符表明属于哪一个类
{
strcpy(name,"");
age = 0;
} //构造函数就是对数据成员进行初始化
CStudent::CStudent(char *name,int age)
{
strcpy(this->name,name);
this->age = age; //从形参传递过来
} //实现两个构造函数
//以上数据成员用_标示了出来,如果使用this指针的话可以用this-
>age=age来实现
/*void CStudent::initialize(char *name,int age)
{ strcpy(this->name,name);
this->age = age;
}
*/
//析构函数的实现
//CStudent::~CStudent()
//{
//cout<<"the object is deconstructing"<<endl;//作为析构
的标记
//}
CStudent::CStudent(const CStudent &student)
{
strcpy(this->name,student.name);
this->age = student.age;
}
void CStudent::output()
{
cout<<name<<" "<<age<<endl;
}
//定义的外部函数,使用引用传递参数
/*
CStudent &input(CStudent &student,char *name, int age)
{
strcpy(student.name,name);
student.age = age;
return student;
}
*/
//普通函数重载
/*
void initialize()
{
cout<<"*********"<<endl;
}
void initialize(int x,int y)
{
cout<<x<<","<<y<<endl;
}
*/
//友元函数的重载
void initialize(CStudent &student)
{
strcpy(student.name,"");
student.age = 0;
}
void initialize(CStudent &student,char *name,int age)
{
strcpy(student.name,name);
student.age = age;
}
//定义对象
void main()
{
CStudent stu1,stu2("Tom",21),stu3(stu2);
stu1.output();
stu2.output();
stu3.output();
initialize(stu2);
stu2.output();
initialize(stu2,"JIM",33);
stu2.output();
}
本文介绍了C++中类的构造函数、拷贝构造函数、静态成员函数及函数重载等概念,并通过具体实例展示了如何定义和使用这些特性。
605

被折叠的 条评论
为什么被折叠?



