c++ 构造与析构函数

#include<iostream>
#include<string.h>
#include<stdlib.h>
using namespace std;
class Test{
    
    
public:
    //构造函数
	Test(){
    
    
		m_x = 0;
		m_y = 0;
	}
	Test(int x,int y){
    
    
		m_x = x;
		m_y = y;
		char *name = (char*)malloc(100);
		strcpy(name,"zhangsan");
	}
	Test(int x){
    
    
		m_x = x;
	
	}
	void print(){
    
    
		cout << "x = " << m_x << ", y = " << m_y << endl;
	}
	//析构函数
	~Test(){
    
    
		cout << "~Test()..." << endl;
		if(name != NULL){
    
    
			free(name);
		}
	}
private:
	int m_x;
	int m_y;
	char *name;
};
int main(){
    
    
	Test t1(10,20);
	Test t2(100);
	Test t3;
	t3.print();
	t2.print();
	t1.print();
	return 0;
} 

猜你喜欢

转载自blog.csdn.net/weixin_46381608/article/details/108549934