struct在C和C++中的使用总结

主要理解一下两点:

1.在C和C++中struct的常规使用。

2.在C++中struct和class基本一致,除了在访问控制权限方面,即:

    通过struct关键字实现的类,属性,函数默认的访问权限为public;
    通过class关键字实现的类,属性,函数默认的访问权限为private。

下面举例说明:

#include<iostream>
using namespace std;

struct point{
	int x;
	int y;
	int fun(point &p)		//在C++中,完全可以在struct中使用函数
	{
		p.x = 100;
		p.y = 200;
		return 0;
	}
	point(int x, int y): x(x) , y(y){ }		//等同于C++中的class
};
struct teacher{
	int age;
	char *name;
};
int main(void){
	point p(0,0);
	p.x = 1;
	p.y = 2;
	point p1= p;
	cout<<"p1.x="<<p1.x<<endl;
	cout<<"p1.y="<<p1.y<<endl;

	point *p3 = &p1;
	p3->x = 10;
	p3->y = 20;
	cout<<"p3->x="<<p3->x<<endl;
	cout<<"p3->y="<<p3->y<<endl;

	p3->fun(p1);
	cout<<"p3->x="<<p3->x<<endl;
	cout<<"p3->y="<<p3->y<<endl;

	point p4(1000,2000);
	cout<<"p4.x="<<p4.x<<endl;
	cout<<"p4.y="<<p4.y<<endl;

	cout<<"================struct在C中用法================"<<endl;
	cout<<"before define struct teacher,sizeof(teacher)="<<sizeof(teacher)<<endl;

	struct teacher t1;				//定义时比较繁琐,需要添加struct关键字,也可以使用typedef声明,此处就不需要加struct关键字。同样在C++中可以直接不加struct关键字

	cout<<"after define struct teacher,sizeof(teacher)="<<sizeof(teacher)<<endl;

	t1.age = 30;
	t1.name = "zhangsan";
	cout<<"t1.age="<<t1.age<<endl;
	cout<<"t1.name="<<t1.name<<endl;

	struct teacher *t2 = &t1;
	t2->age = 35;
	t2->name = "lisi";
	cout<<"t2->age="<<t2->age<<endl;
	cout<<"t2->name="<<t2->name<<endl;

	system("pause");
	return 0;
}

  输出结果:

struct在C和C++中的使用总结

 

原文链接: https://www.cnblogs.com/xuelisheng/p/9221213.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    struct在C和C++中的使用总结

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/276537

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月15日 上午1:49
下一篇 2023年2月15日 上午1:49

相关推荐