c++中的各种用法

c++中的各种用法,第1张

c++中的各种用法

用法目录:

struct:typedef:malloc与free*与&

struct:
#include 
#include 
#include 
//对结构体变量初始化
struct Student
{
	char id[5];
	char name[10];
	int age;
	char sex[3];
}s2={"0002","Mary",15,"女"};
int main()
{
	struct Student s1={"0001","Tom",10,"男"};
	struct Student s3;
	strcpy(s3.id,"0003");
	strcpy(s3.name,"John");
	s3.age=13;
	strcpy(s3.sex,"男");
	system("PAUSE");
	return 0;
}

struct 是C语言中用户用来自定义数据类型的,其只能是一些变量的集合,虽然可以封装数据不能隐藏数据,且成员不可以是函数。struct用法和用int定义整型变量一样,struck就是在程序编辑初要声明的结构体变量。

typedef:
typedef struct k//建立int型数据的二叉树
{
    int data;
    struct k *l,*r;
}btree;

typedef就是用来定义一种类型的新别名
表示:
struct k{……}:定义一个结构体包含data以及l、r;
Typedef struct k btree:将k结构体定义别名btree,即用btree即可定义k结构体类型;
struct k *l,*r:定义指针l、r,可指向struct类型。

注意:经常将typedef与struct同时使用。


malloc与free
ElemType *p=(ElemType *)malloc(sizeof(ElemType)*InitSize);//申请空间
free(p);	//释放空间

malloc是c与c++中用来动态申请空间
free是c与c++中用来释放空间

注意:经常将malloc与free同时使用。


*与&

对于 * 与&分为两种情况:
1.声明时 * 是声明指针,&是声明引用(引用就是某个目标变量的别名)。
2.使用时 * 是解引用,&是取地址。

void fun(int *p,char &x)		//*是定义指针
{
	*p=……;						//*是解引用
}

函数定义时形参里的 * 是定义指针,函数里面使用 * 是解引用。


1.声明引用

#include 
#include 
using namespace std;

int main()
{
    int a=3;
    int &b=a;
    int c=a;
    cout<<"a:"< 

输出:
a:3
b:3
c:3
a:10
b:10
c:3
&a:0x7ffee05caacc
&b:0x7ffee05caacc
&c:0x7ffee05caabc

int &b=a; 是指将a取个别名叫b,改变b的值也就是改变a的值,并不是声明一个新变量b,不占存储单元。

2.声明指针

#include 
#include 
using namespace std;

int main()
{
    int *b,*c,*d;
    int a=10;
    b=&a;           //将a的地址存入指针b,即b指向a
    c=(int *)a;			
    printf("a=%d,b=%d,c=%dn",a,b,c);
    *b=*b+10;			//将b中地址所指向值+10,即a+10
    c=c+10;			//c为int指针型每一个占4字节,则c的值增加40
    printf("a=%d,b=%d,c=%dn",a,b,c);
    d=(int *)malloc(sizeof(int));
    *d=10;
    printf("d=%d,*d=%d",d,*d);
}

输出:
a=10,b=-435508412,c=10
a=20,b=-435508412,c=50
d=-1908407440,*d=10

创建一个指针可指向同类型数据的地址(&取地址或molloc申请空间的地址)


3.解引用
引用其实就是引用该变量的地址,“解"就是把该地址对应的东西解开,解出来,就像打开一个包裹一样,那就是该变量的值了,所以称为"解引用”。


4.取地址
取该变量的地址。


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5715237.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存