C语言之指针、结构体、动态内存分配

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;
}  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Bryan Ding

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值