1 头文件
编译------只编译 当前的 CPP文件 .h文件是不能编译的
编译时,如果出现 不认识的 数据类型、函数--------把他们的头文件加上
注意:
初学------只 编译当前的 cpp文件
多个CPP文件 都编译成功了-----再 点击Build(光 Linking)
强调:
在Student.h中 如果用了 #include "Student_college.h" ----Student_college.h中 也用了#include "Student.h"
则 2个类之间为 双向依赖-----强双向依赖-------导致 编译不过
2 静态成员变量 静态成员函数
语法:
在.h中,在某个成员函数 前 加 static
什么时候,需要将 某个成员函数 定义为 静态?
工具类 下的 成员函数。
数学类-----工具类
包含的静态成员函数:sum max min
静态成员函数的代码:
//main.cpp
#include <iostream>
#include "Math.h"
using namespace std;
/*
int sum(int a,int b)
{
return a+b;
}*/
int main()
{
/*
int a=10;
int b=20;
int result=sum(a,b);
cout<<"sum is "<<result<<endl;*/
/*
CMath math;
int result=math.sum(10,20);
cout<<"sum is "<<result<<endl;*/
int result=CMath::sum(10,20);
cout<<"sum is "<<result<<endl;
return 0;
}
//Math.h
class CMath
{
public:
CMath();
virtual ~CMath();
static int sum(int a,int b);
};
//Math.cpp
#include "Math.h"
CMath::CMath()
{
}
CMath::~CMath()
{
}
int CMath::sum(int a,int b)
{
return a+b;
}
3 静态成员变量
-----肯定会 用到 静态成员函数
为什么使用 静态成员变量?
因为不让使用 全局变量。
语法:
在.h中,在普通的成员变量前 加 static
在.cpp中,初始化 静态成员变量为 0---- int CStudent::total=0;
在.cpp中,所有的成员函数,都可以操作该 静态成员变量 ------ 本例中,构造函数 操作 它
注意:
静态成员函数 只能访问 静态成员变量
如 本例,getTotal()函数,就只能访问 total
代码:
//main.cpp
#include <iostream>
#include "Student.h"
using namespace std;
//int total=0;
int main()
{
CStudent stu1(1001,"aa");
CStudent stu2(1002,"bb");
CStudent stu3(1003,"cc");
cout<<"total is "<<CStudent::getTotal()<<endl;
cout<<"total is "<<stu1.getTotal()<<endl;
cout<<"total is "<<stu2.getTotal()<<endl;
cout<<"total is "<<stu3.getTotal()<<endl;
return 0;
}
//Student.h
class CStudent
{
int number;
char *name;
static int total;
public:
CStudent();
virtual ~CStudent();
CStudent(int number,char *name);
static int getTotal();
};
//Student.cpp
// Student.cpp: implementation of the CStudent class.
//
//
#include <iostream>
#include "Student.h"
int CStudent::total=0;
using namespace std;
//
// Construction/Destruction
//
CStudent::CStudent()
{
total++;
}
CStudent::~CStudent()
{
}
CStudent::CStudent(int number,char *name)
{
this->number=number;
this->name=new char[strlen(name)+1];
strcpy(this->name,name);
total++;
}
int CStudent::getTotal()
{
return total;
}