~,没有参数和返回值。
class String{
private:
char* p;
public:
String(int n);
~String();
};
String::~String(){
delete[] p;
}
String::String(int n){
p = new char[n];
}
String 类的成员变量 p 指向动态分配的一片存储空间,用于存放字符串。动态内存分配在构造函数中进行,而空间的释放在析构函数 ~String() 中进行。这样,在其他地方就不用考虑释放空间的事情了。
#include<iostream>
using namespace std;
class CDemo {
public:
~CDemo() { //析构函数
cout << "Destructor called"<<endl;
}
};
int main() {
CDemo array[2]; //构造函数调用2次
CDemo* pTest = new CDemo; //构造函数调用
delete pTest; //析构函数调用
cout << "-----------------------" << endl;
pTest = new CDemo[2]; //构造函数调用2次
delete[] pTest; //析构函数调用2次
cout << "Main ends." << endl;
return 0;
}
程序的输出结果是:
#include <iostream>
using namespace std;
class CDemo {
public:
~CDemo() { cout << "destructor" << endl; }
};
void Func(CDemo obj) {
cout << "func" << endl;
}
CDemo d1;
CDemo Test() {
cout << "test" << endl;
return d1;
}
int main() {
CDemo d2;
Func(d2);
Test();
cout << "after test" << endl;
return 0;
}
程序的输出结果是:
版权说明:Copyright © 广州松河信息科技有限公司 2005-2025 版权所有 粤ICP备16019765号
广州松河信息科技有限公司 版权所有