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

  輸出結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM