1、内存申请
如果要申请20个结构体complex,那么可以这样写:
C的内存申请:
complex arr = (complex*) malloc(20*sizeof(complex)) ;
C++:
释放:
complex arr = new complex[20]
delete arr
申请时自动出构造,释放时自动出析构。
释放已释放的内存会崩
2、函数模板
防止多次写相同的东西,注意只能在参数数量相同的情况下能用
格式是这样的:
/*template A(A是template的类型)
返回类型 函数名 参数表
{函数体}
*/
template t1, t2
t1 max(t1 a, t2 b)
{
return a>b?a:b;
}
/*这个函数会返回t1类型的值*/
/*调用如下*/
int a =10; float b = 10.212;
cout<<max(a,b)<<endl;
/*t1是int,t2是float,会返回b的t1类型值,即10*/
3、类和对象
·类的定义
class student/*class是关键字*/
{
public:
student(int id)
void input(int id, float score, char *name);
void modify(float s);
void display();
~student(int id)
private:
int id;
float score;
char *name;
}
将上面这个文件保存为student.h。
#include <student.h>
student::student(int id)
{
this->id = id;
}
void student::modify(float s)
{
this->score = s;
}
void display()
{
cout<<'学号是'<<this->id<<'分数是'<<this->score<<endl;
}
将上面这段代码保存为student.cpp。
#include"student.h"
#include<iostream>
using namespace std;
int main()
{
student stu(1);
stu1.modify(89.2);
stu1.display();
}
将下面这段代码保存为stu1.cpp
注意,上面出现了一个东东叫this。
this的作用是联系成员函数和成员对象。即在成员函数中,我们该怎么把形参的值赋给成员变量呢?答案是用this去指向你要赋值的成员变量。this的本质是随成员函数产生而产生的一个指针,是个成员函数的形参,指向对象的地址。
类——>对象——>成员函数、成员变量;其中,在定义成员函数时,成员变量和成员函数有一种方法连接,那就是使用this这个指针;类和成员函数有一种方法连接,那就是在声明的时候加上student::modify(float s)。
在main函数中是用成员函数时,有两种方法把成员函数和对象连接起来,一个是通过 . :stu1.modify;另一种是通过定义指针: Student *pstu = new Student;
pstu -> setname(“李华”);。