构造函数就是例的对像被创建的时候执行的函数,用于初始化对像的内容.(如果需要)
析构函数是例的对像被销毁的时候执行的函数,用于施放对像的资源.(如果有)
如:
calss A:
{
int x;
public A() //构造函数
{
x = 0;
printf("init ok!\n");
}
public ~A() //析构函数
{
printf("beybey!\n");
}
};
int main()
{
A a;
printf("hello!\n";
}
运行和会显示:
init ok! (A a是创建对像a,调构造函数)
hello!(主函数输出)
beybey.(主函数退出前会销毁a,调析构函数)
构造函数 就是对象被创建的时候调用
析构函数 就是对象被销毁的时候调用
#include
using namespace std;
class Line
{
public:
void setLength( double len );
double getLength( void );
Line(); // This is the constructor declaration
~Line(); // This is the destructor: declaration
private:
double length;
};
// Member functions definitions including constructor
Line::Line(void)
{
cout << "Object is being created" << endl;
}
Line::~Line(void)
{
cout << "Object is being deleted" << endl;
}
void Line::setLength( double len )
{
length = len;
}
double Line::getLength( void )
{
return length;
}
// Main function for the program
int main( )
{
Line line;
// set line length
line.setLength(6.0);
cout << "Length of line : " << line.getLength() <
return 0;
}
关于C++的问题都可以问!