-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathstruct.cpp
More file actions
56 lines (45 loc) · 1.27 KB
/
struct.cpp
File metadata and controls
56 lines (45 loc) · 1.27 KB
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/**
* Copyright © https://github.com/microwind All rights reserved.
* @author: jarryli@gmail.com
* @version: 1.0
* @description: 结构体数据结构 - C++实现
*/
#include <iostream>
#include <string>
// Person 结构体:姓名、年龄、地址
struct Person
{
std::string name;
int age;
std::string address;
Person(std::string n, int a, std::string addr) : name(n), age(a), address(addr) {}
void introduce()
{
std::cout << "Hi, I am " << name << ", " << age << " years old, from " << address << "." << std::endl;
}
};
// Employee 结构体:继承 Person,加职位
struct Employee : public Person
{
std::string position;
Employee(std::string n, int a, std::string addr, std::string pos)
: Person(n, a, addr), position(pos) {}
void introduce()
{
std::cout << "I am " << name << ", a " << position << " at the company, living in " << address << "." << std::endl;
}
};
int main()
{
Person p1("Alice", 30, "123 Main St");
p1.introduce();
Employee e1("Bob", 28, "456 Elm St", "Software Developer");
e1.introduce();
return 0;
}
/*
jarry@MacBook-Pro struct % g++ struct.cpp
jarry@MacBook-Pro struct % ./a.out
Hi, I am Alice, 30 years old, from 123 Main St.
I am Bob, a Software Developer at the company, living in 456 Elm St.
*/