在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
学习C++ -> 复制构造函数
int a = 10; int b = a; 使用a变量来初始化b变量, 同样, 对于类创建的对象也可以用这种方式使用一个对象去初始化另一个对象。例如还在上篇中介绍的 Point 类中, 使用一个对象去初始化另一个对象:
View Code - Point.h
1 //Point.h 2 #include <iostream> 3 4 class Point 5 { 6 public: 7 Point(int x = 0, int y = 0):xPos(x), yPos(y) {} 8 void printPoint() 9 { 10 std::cout<<"xPos = "<< xPos <<std::endl; 11 std::cout<<"yPOs = "<< yPos <<std::endl; 12 } 13 14 private: 15 int xPos; 16 int yPos; 17 };
1 #include "Point.h" 2 3 int main() 4 { 5 Point M(10, 20); 6 Point N = M; //使用对象 M 初始化对象 N 7 N.printPoint(); 8 9 return 0; 10 }
xPos = 10 yPOs = 20 Process returned 0 (0x0) execution time : 0.462 s Press any key to continue. Point::Point( const Point & );
1 #include <iostream> 2 #include <cstring> 3 4 using namespace std; 5 6 class Book 7 { 8 public: 9 Book( const char *name ) 10 { 11 bookName = new char [strlen(name)+1]; //使用 new 申请 strlen(name)+1 大小的空间 12 strcpy(bookName, name); 13 } 14 ~Book() { delete []bookName; } //释放申请的空间 15 void showName(){ cout<<"Book name: " << bookName << endl; } 16 17 private: 18 char *bookName; 19 }; 20 21 int main() 22 { 23 Book CPP("C++ Primer"); 24 Book T(CPP); //使用 CPP 初始化对象 T 25 CPP.showName(); 26 CPP.~Book(); //手动释放对象CPP所申请的空间 27 28 T.showName(); 29 30 return 0; 31 }
Book name: C++ Primer Book name: Process returned 0 (0x0) execution time : 0.281 s Press any key to continue. Book( const Book &obj )
{
bookName = obj.bookName;
}
1 #include <iostream> 2 #include <cstring> 3 4 using namespace std; 5 6 class Book 7 { 8 public: 9 Book( const char *name ) 10 { 11 bookName = new char [strlen(name)+1]; 12 strcpy(bookName, name); 13 } 14 Book( const Book &obj ) //显式定义复制构造函数 15 { 16 bookName = new char [strlen(obj.bookName)+1]; //调用复制构造函数时再次申请一处新的空间 17 strcpy(bookName, obj.bookName); 18 } 19 ~Book() { delete []bookName; } //释放申请的空间 20 void showName(){ cout<<"Book name: " << bookName << endl; } 21 22 private: 23 char *bookName; 24 }; 25 26 int main() 27 { 28 Book CPP("C++ Primer"); 29 Book T = CPP; //使用 CPP 初始化对象 T 30 CPP.showName(); 31 CPP.~Book(); //手动释放对象CPP所申请的空间 32 33 T.showName(); 34 35 return 0; 36 }
Book name: C++ Primer Book name: C++ Primer Process returned 0 (0x0) execution time : 0.281 s Press any key to continue.
上一篇: 学习C++ -> 构造函数与析构函数
|
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论