C++学习记录(四)分文件编程,拷贝构造函数
程序虽然能跑通,但是有提示内存泄漏。
1 #ifndef STUDENT_H 2 #define STUDENT_H 3 #include <iostream> 4 5 using namespace std; 6 7 class Student 8 { 9 string name; 10 int age; 11 static int score; 12 int *p; 13 14 public: 15 Student() = default; 16 Student(string name, int age); 17 Student(Student& Student); // 拷贝构造函数 18 19 ~Student() ; 20 21 void showInfo(); 22 int getScore(); 23 24 int getAge(); 25 string getName(); 26 }; 27 28 #endif // STUDENT_H
1 #include "student.h" 2 3 Student::Student(string name, int age) 4 { 5 this->name = name; 6 this->age = age; 7 p = new int[10]; 8 cout << "This is the Student class construction !" << endl; 9 } 10 11 // 浅拷贝(类中有指针时,新拷贝对象和拷贝对象指向内存中的同一地址,故不能多次释放) 12 Student::Student(Student &student) 13 { 14 this->name = student.name; 15 this->age = student.age; 16 cout << "This is the Student class copy construction !" << endl; 17 18 // 深拷贝(类中有指针) 19 this->p = new int[10]; 20 memcpy(this->p, student.p, sizeof(int[10])); // 内存拷贝 21 } 22 23 Student::~Student() 24 { 25 delete []p; 26 } 27 28 void Student::showInfo() 29 { 30 cout << "name is: " << name << ", age: " << age << ", score: " << getScore() << endl; 31 } 32 33 int Student::getScore() 34 { 35 return score; 36 } 37 38 int Student::getAge() 39 { 40 return age; 41 } 42 43 string Student::getName() 44 { 45 return name; 46 } 47 48 int Student::score = 100;
1 #include <iostream> 2 3 using namespace std; 4 5 #include "student.h" 6 7 /* 8 Student compair(Student stu1, Student stu2) 9 { 10 return stu1.getAge() > stu2.getAge() ? stu1: stu2; 11 } 12 */ 13 Student& compair(Student& stu1, Student& stu2) 14 { 15 return stu1.getAge() > stu2.getAge() ? stu1: stu2; 16 } 17 18 int main() 19 { 20 Student stu1; 21 Student stu2("zhangsan", 18); 22 23 stu1.showInfo(); 24 cout << "-------1------" << endl; 25 stu2.showInfo(); 26 27 Student stu3 = stu2; // 拷贝构造函数的两种格式 28 Student stu4(stu2); 29 cout << "-------2------" << endl; 30 stu3.showInfo(); 31 32 // 拷贝构造函数 33 // 当定义对象需要另一个对象初始化时,就会调用拷贝构造函数. 34 // 采用引用的方式,指向同一个内存空间,就不会调用拷贝构造函数,节省空间 35 cout << "------3-------" << endl; 36 Student stu5("Lisi", 20); 37 38 // 当函数传参,函数返回时,会调用拷贝构造函数 39 cout << "The older student is: " << compair(stu2, stu5).getName() << endl; 40 41 cout << "Hello World!" << endl; 42 return 0; 43 }