C++类基本语法实例分析

2025-05-27 0 87

C++程序设计非常重要的概念,本文即以实例形式说明了的常见用法。具体如下:

本测试代码主要包括以下内容:

(1)如何使用构造函数;
(2)默认构造函数;
(3)对象间赋值;
(4)const使用语法
(5)定义常量: 一种方法是用enum,另一种方法是使用static。

实例代码如下:

?

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

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87
#include <iostream>

using namespace std;

enum sexType

{

MAN,

WOMAN

};

class Human

{

//the default is private

private:

string name;

sexType sex;

int age;

//(5) 定义类常量: 一种方法是用enum,另一种方法是使用static

enum{LEN=1};

static const int LEN2 = 3;

public:

//如果类定义中没有提供任何构造函数,则编译器提供默认构造函数。但,如果类中定义了构造函数,那么编写者必须同时提供一个默认构造函数。

//有两种方法提供默认构造函数:

//(1) 定义一个没有参数的构造函数:Human();

//(2) 为非默认构造函数的参数提供默认值: Human(string m_name="no name", int m_age=0, sexType m_sex=MAN);

//两种定义方式只能二选一

Human();

Human(string m_name, int m_age, sexType m_sex);

Human(int m_age);

~Human();

//定义在类声明中的方法为内联方法。也可以使用inline关键字将函数定义在类声明外部。

void show() const //const加在函数名后面表示该函数不会修改该类的数据成员。

{

cout<<"This is "<<name<<", sex: "<<sex<<", "<<age<<" Years old."<<endl;

}

};

Human::Human()

{

cout<<"default construct function"<<endl;

}

Human::Human(string m_name, int m_age, sexType m_sex)

{

cout<<"construct function: "<<m_name<<endl;

name = m_name;

age = m_age;

sex = m_sex;

}

Human::Human(int m_age)

{

age = m_age;

}

Human::~Human()

{

cout<<"destroy function: "<<name<<endl;

}

int main()

{

cout << "This is test code of C++ class: "<< endl;

{

//(1) use of construct function

Human jack = Human("Jack", 30, MAN); //显示调用

Human jerry("Jerry", 26, MAN); //隐式调用

Human *pTom = new Human("Tom", 10, MAN); //New调用

//当构造函数只有一个参数时,可以直接用赋值语句赋值。只有一个参数的构造函数将会被自动调用

Human marry = 11; //赋值调用

//(2) defaults construct function

Human Lucy;

//(3) 赋值对象

Human James;

James = Human("James", 28, MAN); //创建一个临时对象James,copy一份儿该对象赋值给James变量。紧接着该临时对象会被销毁。

//(4) const

const Human Thomas("Thomas", 29, MAN);

Thomas.show(); //The show method must define with 'const'

}

return 0;

}

程序运行结果为:

C++类基本语法实例分析

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 C++类基本语法实例分析 https://www.kuaiidc.com/75918.html

相关文章

发表评论
暂无评论