main.cpp 1.6 KB
Newer Older
1
#include <iostream>
code_shenbing's avatar
code_shenbing 已提交
2
#include "Student.h"  //在使用自定义类之前,需要导入对应的头文件
3
#include "Book.h"
W
wsb 已提交
4
#include "friendFunc.h"
5 6 7

int main() {

code_shenbing's avatar
code_shenbing 已提交
8 9 10 11
    //使用自定义类 Student
    Student student; //定义一个类类型变量student,在创建student变量后默认会调用无参构造方法
    //给变量成员赋值
    student.name = "张三";
12
    student.age = 34;
code_shenbing's avatar
code_shenbing 已提交
13
    student.hobby = "打篮球";
14

code_shenbing's avatar
code_shenbing 已提交
15
    //调用类方法,输出学习信息
16 17
    student.StudentInfo(student);

code_shenbing's avatar
code_shenbing 已提交
18
    //访问类的成员
19
    cout << student.name << "," << student.age << "," << student.hobby << endl;
20

code_shenbing's avatar
code_shenbing 已提交
21 22
    //使用有参构造方法
    Student student1("小李", 22, "滑冰");
23 24
    student1.StudentInfo(student1);

code_shenbing's avatar
code_shenbing 已提交
25 26
    //使用有参构造方法: 使用初始化列表的构造方法
    Student student2("小明", 29);
27 28
    student2.StudentInfo(student2);

code_shenbing's avatar
code_shenbing 已提交
29 30 31
    //拷贝构造函数: 他是用于拷贝一个已有的对象来初始化一个新的对象的函数,
    // 如果类带有指针变量,并有动态内存分配,则它必须有一个拷贝构造函数。
    Student student3 = student; //编译器自动创建默认的拷贝构造函数,把student对象拷贝给student3
32 33
    student3.StudentInfo(student3);

code_shenbing's avatar
code_shenbing 已提交
34
    //演示拷贝构造函数的基本使用!
35 36 37
    Book book(1999);
    book.disValue(book);

38

W
wsb 已提交
39 40 41 42 43 44 45 46
    //给类成员赋值
    friendFunc friendFunc;
    friendFunc.name="friendFunc";
    friendFunc.age=35;
    friendFunc.setHobby("打羽毛球"); //若是普通的访问方式,需要使用set方法来访问被private修饰的变量
    //使用友元函数访问类的任意成员
    printInfo(friendFunc);

47 48
    return 0;
}