复合结构(C++ Primer)
使用结构体和string
使用结构体示例代码:
#include <iostream>
#include <string>
using namespace std;
struct person{
string fn;
string sn;
char grade;
int age;
};
int main(){
person *a=new person;
cout<<"what is your first name?";
cin>>a->fn;
cout<<endl;
cout<<"what is your last name?";
cin>>a->sn;
cout<<endl;
cout<<"what letter grade do you deserve?";
cin>>a->grade;
cout<<endl;
cout<<"what is your age?";
cin>>a->age;
cout<<"Name:"<<(*a).fn<<(*a).sn<<endl;
cout<<"Grade:"<<(char)((*a).grade+1)<<endl;
cout<<"Age:"<<(*a).age<<endl;
delete a;
return 0;
}
这部分代码很好的给出了什么时候用据点运算符,什么时候用->运算符。简单来讲,当前者是结构体名时,就是用句点,当前者是指向结构体的指针时就是用->运算符。
当使用ascii码时,想要进行符号运算(*a).grade+1,符号会被转换成整数型,所以前面要加上转换类型(char)。
输出结果:
what is your first name?wuqing
what is your last name?maliao
what letter grade do you deserve?A
what is your age?23
Name:wuqingmaliao
Grade:B
Age:23
不使用new来分配内存,同时也不使用string而是用char数组,实例代码:
#include <iostream>
using namespace std;
struct person{
char fn[20];
char sn[20];
char grade;
int age;
};
int main(){
person a;
cout<<"what is your first name?";
cin>>a.fn;
cout<<endl;
cout<<"what is your last name?";
cin>>a.sn;
cout<<endl;
cout<<"what letter grade do you deserve?";
cin>>a.grade;
cout<<endl;
cout<<"what is your age?";
cin>>a.age;
cout<<"Name:"<<a.fn<<a.sn<<endl;
cout<<"Grade:"<<(char)(a.grade+1)<<endl;
cout<<"Age:"<<a.age<<endl;
return 0;
}
结构体数组
定义一个结构体,声明结构体数组并初始化。
示例代码:
#include <iostream>
#include <string>
using namespace std;
struct CandyBar
{
string name;
double weight;
int kaLuLi;
};
int main(){
CandyBar a[3]={{"A",12.3,8},{"B",50.6,76},{"C",54.9,126}};
for(int i=0;i<3;i++){
cout <<a[i].name<<" ";
cout <<a[i].weight<<" ";
cout <<a[i].kaLuLi<<endl;
}
return 0;
}
运行结果:
A 12.3 8
B 50.6 76
C 54.9 126
使用new来为结构分配内存:
#include <iostream>
#include <string>
using namespace std;
struct CandyBar
{
string name;
double weight;
int kaLuLi;
};
int main(){
CandyBar *b[3]={new CandyBar, new CandyBar, new CandyBar };
for(int i=0;i<3;i++){
b[i]->name="a";
b[i]->weight=36.8+i;
b[i]->kaLuLi=23+i;
}
for(int i=0;i<3;i++){
cout <<b[i]->name<<" ";
cout <<b[i]->weight<<" ";
cout <<b[i]->kaLuLi<<endl;
}
delete b[3];
return 0;
}
运行结果:
a 36.8 23
a 37.8 24
a 38.8 25
标签:CandyBar,include,cout,int,复合,C++,new,Primer,string
From: https://www.cnblogs.com/wuqingmaliao/p/18520510