CPP学习之——结构体与构造函数(18.15)

一 概述

本文将上节代码的基础上,为结构体添加一个构造函数,重新上述代码。

二 示例演示及结果输出

2.1 代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include<iostream>
#include<cstring>
using namespace std;
struct people
{
people(int t_age,double t_weight,double t_tall,string t_name,string t_native,bool t_sex);
int age;
double weight;
double tall;
string name;
string native;
bool sex;
};
void check(bool s){if(s==1)cout<<"男"<<endl;else cout<<"女"<<endl;}
int main()
{
people Jack(34,170.3,180.5,"Jack","济南",1);
cout<<Jack.name<<endl;
cout<<Jack.native<<endl;
cout<<Jack.tall<<endl;
cout<<Jack.weight<<endl;
cout<<Jack.age<<endl;
check(Jack.sex);

return 0;
}
people::people(int t_age,double t_weight,double t_tall,string t_name,string t_native,bool t_sex){
age=t_age;
weight=t_weight;
tall=t_tall;
name=t_name;
native=t_native;
sex=t_sex;
}

2.2 输出结果

1
2
3
4
5
6
Jack
济南
180.5
170.3
34

2.3 总结

  • 在这个程序中,我们使用了构造函数对string型字符串进行赋值,由于调用的是构造函数,所以Jack后面没有加赋值运算符(=),并且用小括号替代了大括号

三 结构体的赋值

3.1 代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include<iostream>
using namespace std;
struct people
{
double weight;
double tall;
};
int main()
{
people Mike={185.2,178.1};
people Jack={65.4,165.2};
Mike=Jack;
cout<<Mike.weight<<" "<<Mike.tall<<endl;
cout<<Jack.weight<<" "<<Jack.tall<<endl;
return 0;
}

3.2 输出结果

1
2
65.4 165.2
65.4 165.2