马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 liuzhengyuan 于 2020-5-8 17:10 编辑
我的 C++ 自学心得 | 003 - 类和对象(class & object)② 结构函数(Constructor Functions)
0,构造函数
什么是构造函数?
它里面的程序是在我们创建对象时进行的。
如何做构造函数?
看代码:
这个代码(在下方)中
就是一个构造函数。
它里面的程序是在我们创建对象时进行的,且这段程序创建了两个对象
所以它会输出两次 "creating object..." - #include<bits/stdc++.h>
- using namespace std;
- class Book {
- public:
- string name;
- string author;
- int pages;
- //构造函数!!!
- Book() {
- cout<<"creating object..."<<endl;
- }
- };
- int main()
- {
- Book b1;
- b1.name="Harry Potter";
- b1.author="JK";
- b1.pages=500;
-
- Book b2;
- b2.name="lingjichu";
- b2.author="xiaojiayu";
- b2.pages=600;
-
- return 0;
- }
复制代码
效果:
- creating object...
- creating object...
复制代码
更多玩法
它还能有参数
这次的代码(在下方)有 2 处重点了
- Book b1("感谢 小甲鱼");
- Book b2("感谢 鱼C论坛");
复制代码 这个括号里的内容就是参数↑
而且 Book 函数的程序就是让参数输出↓
- Book(string temp) {
- cout<<temp<<endl;
- }
复制代码
这样,屏幕就会显示 “感谢 小甲鱼,感谢 鱼C论坛” 的字样了
(DEV-C++ 支持中文) - #include<bits/stdc++.h>
- using namespace std;
- class Book {
- public:
- string name;
- string author;
- int pages;
- Book(string temp) {
- cout<<temp<<endl;
- }
- };
- int main()
- {
- Book b1("感谢 小甲鱼");
- b1.name="Harry Potter";
- b1.author="JK";
- b1.pages=500;
-
- Book b2("感谢 鱼C论坛");
- b2.name="lingjichu";
- b2.author="xiaojiayu";
- b2.pages=600;
-
- return 0;
- }
复制代码
效果:
如果我要用普通的方法创建4各和上方一样关于书本的对象,并赋值
就要花 4 * 4 = 16 行,
如果我想创建 20 个,并赋值
就要花 20 * 4 = 80 行,
那如果 100 个,300 个呢?
300 * 4 = 1200 行、
如何使用更少的行数,创建更多的对象并赋值呢?
上结构函数的代码:
- Book(string a_name, string a_author, int a_pages) {
- name=a_name;
- author=a_author;
- pages=a_pages;
- }
复制代码
很简单
程序定义了 3 个参数
以后我们想要赋值就直接:
- Book b1("Harry Potter", "JK", 500);
- Book b2("lingjichu", "xiaojiayu", 600);
复制代码
整整少了 3 行
再试试输出:-
- cout<<b1.name<<endl;
- cout<<b2.pages<<endl;
复制代码
效果:
还可以定义两个,第一个函数会在没有任何参数的时候执行:
- #include<bits/stdc++.h>
- using namespace std;
- class Book {
- public:
- string name;
- string author;
- int pages;
-
- Book() {
- name="No name";
- author="No author";
- pages=0;
- }
-
- Book(string a_name, string a_author, int a_pages) {
- name=a_name;
- author=a_author;
- pages=a_pages;
- }
- };
- int main()
- {
- Book b1;
-
- cout<<b1.name<<endl;
- cout<<b1.pages<<endl;
-
- return 0;
- }
复制代码
效果:
结束啦
|