根据实例复习Cpp


1. 还是这里开始Cpp


view plaincopy to clipboardprint?
1. #include
2. // 一个良好的编程习惯是将using直接跟在include之后
3. usingnamespacestd;
4. intmain()
5. {
6. intnumber1;
7. intnumber2;
8. intsum;
9. cout <<"Enter the first number :";
10. cin >> number1;
11. cout <<"Enter the second number :";
12. cin >> number2;
13. sum = number1 + number2;
14. // <<流操作符
15. cout <<"Sum is "<< sum << endl;
16.
17. return0;
18. }

2. 定义第一个类

view plaincopy to clipboardprint?
1. // 定义第一个类
2. #include
3. usingnamespacestd;
4. classGradeBook
5. {
6. public:// 访问修饰符
7. // 定义类方法
8. voiddisplayMessage()
9. {
10. cout <<"Welcome to GradeBook"<< endl;
11. }
12. };// 注意这里的分号
13. intmain()
14. {
15. // 声明GradeBook类,区分这里和c#中需要使用new关键字
16. GradeBook g;
17. g.displayMessage();
18.
19. return0;
20. }

  1. 使用string对象

view plaincopy to clipboardprint?
1. // 使用string对象
2. #include
3. #include
4. usingnamespacestd;
5. intmain()
6. {
7. // 声明string对象str
8. string str;
9. // 读取一行
10. getline(cin, str);
11. // 输出
12. cout << str;
13.
14. return0;
15. }

  1. 类构造函数

view plaincopy to clipboardprint?
1. // 测试类的构造函数
2. //
3. // 如果一个类没有提供构造函数的话,编译器将生成一个默认的
4. // 构造函数,在该构造函数中将调用类中每个数据程序的默认构造函数
5. #include
6. usingnamespacestd;
7. classStudent
8. {
9. public:
10. Student()
11. {
12. cout <<"Call Student default constructor\n";
13. this->score = 0.0;
14. }
15. private:
16. doublescore;
17. };
18. classGradeBook
19. {
20. public:
21. intgetData()
22. {
23. returndata;
24. }
25. private:
26. Student stu;
27. intdata;
28. };
29. intmain()
30. {
31. // 在类GradeBook中没有构造函数,那么编译器将生成一个默认构造函数
32. // 将调用Student的默认构造函数,但是data的值是不确定
33. GradeBook g;
34. cout << g.getData() << endl;
35. return0;
36. }

  1. Cpp中类定义和实现分文件

// Main.cpp

view plaincopy to clipboardprint?
1. #include
2. // 包含类定义头文件
3. #include "GradeBook.h"
4. intmain()
5. {
6. GradeBook g;
7. g.displayMsg();
8. return0;
9. }

// GradeBook.h

view plaincopy to clipboardprint?
1. #ifndef GRADE_BOOK_H
2. #define GRADE_BOOK_H
3. // 仅仅是类定义
4. classGradeBook
5. {
6. private:
7. doubledata;
8. public:
9. voiddisplayMsg();
10. GradeBook();
11. };
12. #endif

// GradeBook.cpp

view plaincopy to clipboardprint?
1. #include
2. usingstd::cout;
3. #include "GradeBook.h"
4. // 类实现
5. GradeBook::GradeBook()
6. {
7. this->data = 0.0;
8. }
9. voidGradeBook::displayMsg()
10. {
11. cout <<"Welcome to GradeBook !\n";
12. }

6.else摇摆

view plaincopy to clipboardprint?
1. // 控制结构:else摇摆
2. #include
3. usingnamespacestd;
4. intmain()
5. {
6. intx = 3, y = 6;
7. if(x > 5)
8. if(y > 5)
9. cout <<"x and y are > 5"<< endl;
10. else// 这里的else匹配的是最近的那个if
11. // 下面的程序将什么也不输出,因为x < 5
12. cout <<"x is <= 5";
13. return0;
14. }

  1. 存储类别,链接和作用域

这里有介绍,但是需要指明的是存储类别和作用域是相互独立的,不是说一个变量V在程序的整个运行期间都存在,并不代表在任何的作用域中该变量均能使用。

8.内联函数

view plaincopy to clipboardprint?
1. // 内联函数
2. #include
3. usingnamespacestd;
4. // 使用管理之inline表明向编译器提出申请将这个
5. // 函数内敛
6. inlineintmax(inta,intb)
7. {
8. return(a > b) ? a : b;
9. }
10. intmain()
11. {
12. return0;
13. }



9. cpp中的引用

view plaincopy to clipboardprint?
1. // cpp中的引用类型
2. #include
3. usingnamespacestd;
4. // 在函数参数中使用引用
5. voidincrease(int& a)
6. {
7. a++;
8. }
9. // 使用const表明的是在该函数中不改变a的值
10. voidprint(constint& a)
11. {
12. // 将出现错误 a = 1;
13. cout << a << endl;
14. }
15. intmain()
16. {
17. intvalue = 0;
18. // 声明引用,并赋值
19. int& refValue = value;
20. // refValue和value指向的是同一个对象,所以更改refValue的值将
21. // 更改value的值
22. refValue = 5;
23. cout <<"the value is :"<< value << endl;
24. inta = 0;
25. // 注意这里的函数调用方式,这里和普通的函数调用是相类似的,
26. // 但是却在函数内部改变了a的值
27. increase(a);
28. cout <<"after Increase, a is "
29. << a << endl;
30. return0;
31. }
10. 默认实参

view plaincopy to clipboardprint?
1. // cpp默认实参
2. #include
3. usingnamespacestd;
4. // 默认参数,语法的格式是直接在函数的形式参数中写入
5. // 默认值
6. intboxVolume(intlength = 1,
7. intwidth = 1,
8. intheight = 1)
9. {
10. return(length * width * height);
11. }
12. intmain()
13. {
14. // 含有默认参数的函数的调用
15. cout <<"1, 1, 1 is "<< boxVolume() << endl;
16. cout <<"1, 2, 1 is "<< boxVolume(1, 2) << endl;
17. cout <<"1, 2, 3 is "<< boxVolume(1, 2, 3) << endl;
18. return0;
19. }
11.一元作用域分辨运算符

view plaincopy to clipboardprint?
1. // 一元作用域分辨运算符
2. #include
3. usingnamespacestd;
4. // 全局变量
5. intnum = 10;
6. intmain()
7. {
8. // 局部变量
9. intnum = 5;
10. cout <<"local is "<< num << endl;
11. // 使用::来访问全局num变量
12. cout <<"global is "<< ::num << endl;
13. return0;
14. }
12.函数重载

view plaincopy to clipboardprint?
1. // 函数重载
2. #include
3. usingnamespacestd;
4. // 重载其他比较迷惑特性:默认参数重载,引用类型重载,const类型重载
5. // 函数重载:c++在进行函数重载时只是根据函数的参数的
6. // 类型来判断,不根据函数的返回值来区别两个函数,因为在
7. // 编译器对重载函数进行编译时将根据参数的不同类型重新生成
8. // 名字,同时忽略函数的返回值
9. // #1
10. voidoverloadFunc()
11. {
12. cout <<"Call void overloadFunc()"<< endl;
13. }
14. // #2
15. voidoverloadFunc(int)
16. {
17. cout <<"Call void overloadFunc(int)\n";
18. }
19. intmain()
20. {
21. inta = 0;
22. // #2
23. overloadFunc(a);
24. return0;
25. }
13. 函数模板

view plaincopy to clipboardprint?
1. // 函数模板
2. #include
3. usingnamespacestd;
4. template<typenameT>
5. T maxValue(T a, T b)
6. {
7. return(a > b) ? a : b;
8. }
9. intmain()
10. {
11. // 注意这里在使用时,不需要指明类型(max)
12. cout << maxValue(1, 2) << endl;
13. cout << maxValue('a','b') << endl;
14. // 这句将产生错误,两个参数的类型不一致
15. // cout << maxValue('a', 10) << endl;
16. return0;
17. }
14. 函数指针数组

view plaincopy to clipboardprint?
1. // 函数指针数组
2. #include
3. usingnamespacestd;
4. voidfunc1()
5. {
6. }
7. voidfunc2()
8. {
9. }
10. voidfunc3()
11. {
12. }
13. intmain()
14. {
15. // 声明函数指针数组
16. void(*funcPtr[3])();
17. funcPtr[0] = func1;
18. funcPtr[1] = func2;
19. funcPtr[2] = func3;
20. return0;
21. }
15. 何时调用构造函数和析构函数

全局变量的初始化是优先于main函数执行,然后开始执行main函数,在main函数中如果遇到自动变量对象,将调用该变量的构造函数,在该变量的作用域完成之后,将指定调用该变量的析构函数,如果是static变量的话,将在main函数结束之后调用析构函数。如果程序中遇到 exit或者是abort的话,将不调用任何对象的析构函数。

view plaincopy to clipboardprint?
1. // 函数指针数组
2. #include
3. #include
4. usingstd::string;
5. usingstd::cout;
6. usingstd::endl;
7. classCreateAndDestroy
8. {
9. public:
10. CreateAndDestroy(intid, string msg)
11. {
12. m_objectId = id;
13. m_message = msg;
14. cout <<"Object : "<< m_objectId
15. <<" Constructor runs "<< m_message << endl;
16. }
17. ~CreateAndDestroy()
18. {
19. cout <<"Object : "<< m_objectId
20. <<" Destructor runs "<< m_message << endl;
21. }
22. private:
23. intm_objectId;
24. string m_message;
25. };
26. voidcreate()
27. {
28. cout <<"Create function : executuion begins"<< endl;
29. CreateAndDestroy fifth (5,"local automic in create");
30. staticCreateAndDestroy sixth (6,"local static in create");
31. CreateAndDestroy seventh(7,"local automic in create");
32. cout <<"Create function : executuion ends"<< endl;
33. }
34. // 全局变量
35. CreateAndDestroy fist(1,"global before main");
36. intmain()
37. {
38. cout <<"Main function execution begins"<< endl;
39. CreateAndDestroy second(2,"local automic in main");
40. staticCreateAndDestroy third(3,"local static in main");
41.
42. create();
43. cout <<"Main function : execution resumes "<< endl;
44. CreateAndDestroy fourth(4,"local automic in main");
45. cout <<"Main function : execution ends"<< endl;
46.
47. return0;
48. }

  1. const对象和const成员函数

view plaincopy to clipboardprint?
1. // const成员函数
2. #include
3. #include
4. usingstd::string;
5. usingstd::cout;
6. usingstd::endl;
7. // 定义Time类
8. classTime
9. {
10. private:
11. inthour;
12. intminute;
13. intsecond;
14. public:
15. Time(inth = 0,intm = 0,ints = 0)
16. {
17. hour = h;
18. minute = m;
19. second = s;
20. }
21.
22. // set方法
23. // const函数,非const对象能够调用const函数,但是const
24. // 对象只能调用 const成员函数
25. voidprintTime()const
26. {
27. cout <<"hour "<< hour
28. <<" minute "<< minute
29. <<" second "<< second
30. << endl;
31. }
32. };
33. intmain()
34. {
35. // 声明const对象
36. constTime t(1, 1, 1);
37. t.printTime();
38. Time t2;
39. t2.printTime();
40. return0;
41. }

  1. const产量初始化

view plaincopy to clipboardprint?
1. // const产量初始化
2. #include
3. #include
4. usingstd::string;
5. usingstd::cout;
6. usingstd::endl;
7. // 定义Time类
8. classTime
9. {
10. private:
11. constintCONSTANT;
12. public:
13. // const常量初始化语法,如果是const static产量的话,直接在定义处初始化
14. Time() : CONSTANT(0)
15. {
16. }
17. };
18. intmain()
19. {
20. Time t;
21. return0;
22. }

  1. 友元函数

view plaincopy to clipboardprint?
1. // 友元函数
2. #include
3. #include
4. usingstd::string;
5. usingstd::cout;
6. usingstd::endl;
7. // 定义Time类
8. classTime
9. {
10. private:
11. inthour;
12. intminute;
13. intsecond;
14. public:
15. Time(inth = 0 ,intm = 0,ints = 0)
16. {
17. hour = h;
18. minute = m;
19. second = s;
20. }
21. // 定义friend函数。实际上友元函数可以在class的任何位置定义
22. // 因为友元函数实际上不是该类的成员函数
23. friendTime add(constTime& t1,constTime& t2);
24. };
25. // 定义有缘函数,这里不需要使用friend
26. Time add(constTime& t1,constTime& t2)
27. {
28. returnTime(t1.hour + t2.hour,
29. t1.minute + t2.minute,
30. t1.second + t2.second);
31. }
32. intmain()
33. {
34. Time t1(1, 1, 1);
35. Time t2(2, 2, 2);
36. Time t3 = add(t1, t2);
37. return0;
38. }
19. 类中的static成员和static函数

view plaincopy to clipboardprint?
1. // 类中的static成员和static函数
2. #include
3. #include
4. usingstd::string;
5. usingstd::cout;
6. usingstd::endl;
7. // 定义Time类
8. classTime
9. {
10. private:
11. inthour;
12. intminute;
13. intsecond;
14. // 定义static成员变量
15. staticintinstanceCounts;
16. public:
17. Time(inth = 0 ,intm = 0,ints = 0)
18. {
19. hour = h;
20. minute = m;
21. second = s;
22. // 使用类的静态变量
23. Time::instanceCounts++;
24. }
25.
26. // 定义static成员函数
27. staticintgetInstanceCount()
28. {
29. returninstanceCounts;
30. }
31. };
32. // 虽然static成员默认已经进行了初始化为0,但是如果不添加这初始化的话
33. // 在该文件中将找不到该变量
34. intTime::instanceCounts = 0;// 文件作用域
35. intmain()
36. {
37. Time t1(1, 1, 1);
38. Time t2(2, 2, 2);
39.
40. // 使用类的静态方法
41. cout <<"Time instance count is "<< Time::getInstanceCount() << endl;
42. // 调用类的static方法
43.
44. return0;
45. }
20. 运算符重载

运算符重载仅仅是在简化客户端的程序的编程,可以直接调用运算函数:t1.operator==(t2);.

view plaincopy to clipboardprint?
1. // 运算符重载
2. #include
3. #include
4. usingstd::string;
5. usingstd::cout;
6. usingstd::endl;
7. // 定义Time类
8. classTime
9. {
10. private:
11. inthour;
12. intminute;
13. intsecond;
14. public:
15. Time(inth = 0,intm = 0,ints = 0)
16. {
17. hour = h;
18. minute = m;
19. second = s;
20. }
21. // 使用默认构造函数
22. // 运算符重载==
23. booloperator== (constTime& other)
24. {
25. return(hour == other.hour) &&
26. (minute ==other.minute) &&
27. (second == other.second);
28. }
29. // !=
30. booloperator!= (constTime& other)
31. {
32. return!(this== other);
33. }
34. // +
35. Time operator+(constTime& other)
36. {
37. returnTime(hour + other.hour,
38. minute + other.minute,
39. second + other.second);
40. }
41. // -
42. Time operator-(constTime& other)
43. {
44. inthour = hour - other.hour;
45. intminute = minute - other.minute;
46. intsec = second - other.second;
47. returnTime(hour, second, sec);
48. }
49. //

50. Time operator*(intn)
51. {
52. returnTime(hour * n,
53. minute * n,
54. second * n);
55. }
56. // 打印信息
57. voidprintTime()
58. {
59. cout <<"Hour : "<< hour
60. <<" Minute : "<< minute
61. <<" Second : "<< second
62. << endl;
63. }
64. };
65. intmain()
66. {
67. Time t1(1, 1, 1);
68. Time t2(2, 2, 2);
69.
70. Time t3 = t1 + t2;
71. t3.printTime();
72.
73. if(t1 == t2)
74. cout <<"t1 == t2"<< endl;
75. else
76. cout <<"t1 != t2"<< endl;
77. return0;
78. }
21. 类型转换函数

在c++中如果构造函数可以用作类型转换函数(如果想要禁止的话,可以使用关键字explicit禁止将该构造函数用作默认的类型转换函数),也可以指定以类的类型转换函数。

view plaincopy to clipboardprint?
1. // 类型转换函数,这里仅仅是为了演示,没有实际意义
2. // 注意这里的函数格式,没有返回值
3. operatorint()
4. {
5. return1;
6. }
22. 重载++运算符

由于在c++中存在a++和++a的类型,所以编译器需要使用一个所谓的“哑元素”来区分是a++还是++a。

view plaincopy to clipboardprint?
1. // 定义++运算符
2. // ++a形式
3. Time& operator++ ()
4. {
5. second++;
6. return(this);
7. }
8. // a++形式
9. Time operator++(int)
10. {
11. Time tmp =
this;
12. second++;
13. returntmp;
14. }

23.类的继承属性

c++中存在三种类型的继承属性,如果不明确知名的话,默认的是private继承。不管是何种类型的继承,子类都是不能访问父类的private成员的,只是private,public,protected继承对于父类的public成员在子类中的行为是不相同的。同时需要注意的是:

  1. 构造函数是不能够被继承的

  2. 如果子类重写了父类的某个方法 ,但是还想调用覆盖的父类方法时,可以使用父类名::函数的形式调用

24 virtual关键字

view plaincopy to clipboardprint?
1. // 父类
2. classBaseClass
3. {
4. public:
5. BaseClass()
6. {
7. cout <<"base class constructor. "<< endl;
8. }
9. ~BaseClass()
10. {
11. cout <<"baseclass destructor"<< endl;
12. }
13. virtualvoidtoOverrideFunc()
14. {
15. cout <<"override function in baseclass."<< endl;
16. }
17. };
18. // 这里使用的是public继承
19. classSubclass :publicBaseClass
20. {
21. public:
22. Subclass()
23. {
24. // 这里将首先调用BaseClass的构造函数
25. cout <<"subclass constructor. "<< endl;
26. }
27. ~Subclass()
28. {
29. // 这里首先调用该类的析构函数,然后是父类的析构函数
30. cout <<"subclass destructor."<< endl;
31. }
32. // 这里仅隐藏父类的该函数toOverrideFunc
33. virtualvoidtoOverrideFunc()
34. {
35. cout <<"override function in subclass"<< endl;
36. }
37. };
38. intmain()
39. {
40. // 没有使用virtual的话,那么函数调用将取决于调用的句柄
41. // 如果使用了irtual的话,那么函数调用的将取决于实际的对象类型
42. BaseClass basePtr =newSubclass();
43. // 这里将调用subclass中的函数
44. basePtr->toOverrideFunc();
45.
46. Subclass
subPtr =newSubclass();
47. subPtr->toOverrideFunc();
48. deletebasePtr;
49. deletesubPtr;
50.
51. return0;
52. }
25. 抽象类

c++中如果一个类想要成为抽象类的话,只需要将类中的一个成员函数声明为纯虚函数,纯虚函数是不能够有时显得,但是虚函数是能够有函数的时显的。

view plaincopy to clipboardprint?
1. // 纯虚函数
2. #include
3. #include
4. usingstd::string;
5. usingstd::cout;
6. usingstd::endl;
7. usingstd::ostream;
8. usingstd::istream;
9. usingstd::cin;
10. // 父类,抽象类
11. classBaseClass
12. {
13. public:
14. // 纯虚函数
15. virtualvoidpureVirtualFunc()= 0;
16. };
17. // 这里使用的是public继承
18. classSubclass :publicBaseClass
19. {
20. public:
21. virtualvoidpureVirtualFunc()
22. {
23. cout <<"in the subclass, we override the purevirtualFunc()"
24. << endl;
25. }
26. };
27. intmain()
28. {
29. // 抽象类是无法实例化的
30. // BaseClass b; // 错误
31. BaseClass* basePtr =newSubclass();
32. basePtr->pureVirtualFunc();
33. deletebasePtr;
34. return0;
35. }

完结
原文链接: https://www.cnblogs.com/xuqiang/archive/2011/04/22/2024873.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/24404

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月8日 上午2:16
下一篇 2023年2月8日 上午2:17

相关推荐