c++知识点总结--结构体

103 阅读1分钟

结构体

声明时: {;}
初始化时:{,}
结构体声明:

//example:
struct dolly 
{
	char name[20]; 
	float volume; 
	double price;
}; // }inf;

结构体使用:
(struct可以省略)

//example:
struct dolly cat;
dolly hat = {"wwwdfwf",1.88,23.33}; //省略struct 等号也可以省略
//dolly hat("SSS",1.2,23);//必须给出相应有参构造才行。
cat = hat;//copy操作;对成员是地址的结构体还是不要这样copy;会使得两个结构体对象指向同一个地址,类似情况在class中也要考虑,此时应该重写 operator=();
//cat.name;cat.volume 可以来查看,修改,对象的成员值;

结构体数组:
dolly gifts[100]; ---- ---- 创建100个dolly类,即数组的每个元素都是dolly类;

//example
dolly guests[2] = { {"sfwe",0.2,0.4}, {...}, {...},}; 
// dolly guestss[2] ={dolly("ddd",0.2,0.3),...};
guests[0].name="xxx";

结构体指针:

//example:
dolly hat = {"wwwdfwf",1.88,23.33};//创建结构体变量
dolly * p = &hat;//通过指针指向结构体变量;
cout << p->name << p->volume<<endl;//通过指针访问结构变量的数据,使用->来访问;
dolly* q = new dolly{"dsdf",1.2,22,22};

结构体嵌套结构体:

struct student{
 	string name; 
 	int age; 
 	int score;
 };
struct teacher {
	int id; 
	string name; 
	int age; 
	struct student stu;
	};
teacher t;
t.id =1000;
t.name="li";
t.stu.name="小王";
t.stu.age = 20;

结构体作函数参数:

struct student{ 
	string name; 
	int age; 
	int score;
};
void printStudent1(struct student s){
	std::cout<<s.mame<<std::endl;
} //值传递 (函数中用.调用)
void printStudent2(struct student &s){
	std::cout<<s.mame<<std::endl;
} //引用传递 (函数中用.调用)
void printstudent3(struct student * p ){
 std::cout<<p->name<<std::endl;
 } //地址传递 (函数中用->来调用)
int main()
{
	student s; 
	s.name="xxx";
	s.age=20; 
	s.score = 60;
	printStudent1(s);
	return 0;
}

其他相关知识

struct和class高度相似;只不过 struct 默认权限是public;class的默认权限是private;

//example
struct Student
{
	public://可以不写,默认的
		string name;
		int age;
		Student():name("xsd"),age(10),score(99){};
		Student(string s,int a,double sco):name(s),age(a),score(sco){};
	privatedouble score;//外部无法访问
		
};

Student s;//其中name = "xsd" ; age = 10 ; score(99)

上面例子中在struct的二个构造函数使用到初始化列表的方法 —这种方法只能用于构造函数,class或者struct