天天看点

c++结构体基础知识

这次博客记录c++结构体的基础知识,希望能帮助大家

结构的定义

参考书籍 <<c++ primer plus>>

结构是用户定义的类型,而结构声明定义了这种类型的数据属性。定义了这种类型,便可以创建这种类型的变量(对象)

比如:

struct inflatable
{
    char name[20];
    float volume;
    double price;
};
           

我们还可以在结构体放置c++的string类型,里面的类型还可以放置自己自定义的类型比如结构,类。

例如:

#include<iostream>
#include<string>
#define MAXSIZE 20
using namespace std;
struct Student{ 
	    int grade;
	    char ID_card[MAXSIZE];
};
struct Person{
	 string name ;// 使用 c++的string 类型 
	 char phonenumber[MAXSIZE];
	struct Student stu;//自定义类型 结构 
};
int main(){
	 Student s1={100,"2701333456"};//列表初始化
     Person p1={"李四","13285522071",s1};
	 cout<<p1.name<<" "<<p1.phonenumber
     <<" "<<p1.stu.grade<<" "<<p1.stu.ID_card;
	return 0;
}
           

结构的初始化:

在c++11中,支持列表初始化,在c++11之前,如何给字符数组传值呢?

来看代码:

#include<iostream>
#include<string>
#include<cstring>//strcpy
#define MAXSIZE 20
using namespace std;
struct Student{ 
	    int grade;
	   char ID_card[MAXSIZE];
};

int main(){
	 Student s;
	 s.grade=100;
	// s.ID_card="11111111" ;//error 不能用“=”直接为字符数组赋值
	 strcpy(s.ID_card,"1234567");//使用strcpy函数复制字符串
	 cout<<s.grade<<" "<<s.ID_card<<endl;
}
           

大家可以看看这个文章,很有帮助的。

结构体字符数据初始化

结构数组:

Person per[10]; //per是一个数组,per就是一个单纯的数组,不过数组存储的类型为结构类型,反正多想想就清晰了。

那Person 对象是啥呢?

是per[i],就是数组里面存储的每一个数据,都是结构对象

一个代码的例子:

// arrstruc.cpp -- an array of structures
#include <iostream>
#include<string>
struct inflatable
{
    char name[20];
    float volume;
    double price;
};
int main()
{
    using namespace std;
    inflatable guests[2] =          // initializing an array of structs
    {
        {"Bambi", 0.5, 21.99},      // first structure in array
        {"Godzilla", 2000, 565.99}  // next structure in array
    };

    cout << "The guests " << guests[0].name << " and " << guests[1].name
         << "\nhave a combined volume of "
         << guests[0].volume + guests[1].volume << " cubic feet.\n";
    // cin.get();
    return 0; 
}
           

好了,结构体基础知识就到这里了,下回见!

继续阅读