查看构造函数、拷贝构造函数、析构函数的调用情况。
#include <iostream> using namespace std; class Line { public: int getLength( void ); Line( int len, string name); // 简单的构造函数 Line( const Line &obj); // 拷贝构造函数 ~Line(); // 析构函数 string name; private: int *ptr; }; // 成员函数定义,包括构造函数 Line::Line(int len, string n) { // 为指针分配内存 ptr = new int; *ptr = len; name = n; cout << "调用构造函数 " << name << endl; } Line::Line(const Line &obj) { cout << "调用拷贝构造函数 " << obj.name << endl; ptr = new int; *ptr = *obj.ptr; // 拷贝值 name = "~" + obj.name; } Line::~Line(void) { cout << "释放内存 " << name << endl; delete ptr; } int Line::getLength( void ) { return *ptr; } void display(Line obj) { cout << "line 大小 : " << obj.getLength() <<endl; } Line newline(double len) { Line temp_line(len, "temp_line"); return temp_line; } // 程序的主函数 int main( ) { Line line1(10, "direct_line1"); // 直接初始化,调用构造函数 cout << endl; Line line2 = line1; // 拷贝初始化,调用拷贝构造函数 line2.name = "copy_line2"; cout << endl; display(line1); // 一个对象以值传递的方式传入函数体 cout << endl; line1 = newline(8); // 一个对象以值传递的方式从函数返回 cout << line1.name << endl; line1.name = "modified_line1"; cout << endl; display(line2); cout << endl; return 0; }
版权声明:
本文来源网络,所有图片文章版权属于原作者,如有侵权,联系删除。
本文网址:https://www.mushiming.com/mjsbk/8593.html