Cpp学习笔记(1)

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是关键字*/
{
publicstudent(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(“李华”);。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值