c++中构造和析构函数

构造函数:在每次创建对象时调用,没有任何返回值(包括void)可以用来为某些成员变量设置初始值。

下面是几种不同的构造函数:

常见的构造函数:

 1 .h:
 2 
 3  explicit MainWindow(QWidget *parent = 0);
 4 
 5 .c:
 6 
 7 MainWindow::MainWindow(QWidget *parent) :
 8 QMainWindow(parent),
 9 ui(new Ui::MainWindow)
10 {
11 ui->setupUi(this);
12 }
13 
14 .h:
15 
16 explicit Widget(QWidget *parent = 0);
17 
18 .c:
19 
20 Widget::Widget(QWidget *parent) :
21 QWidget(parent),
22 ui(new Ui::Widget)
23 {
24 ui->setupUi(this);
25 }
View Code

带参数的构造函数:

默认的构造函数没有任何参数,但如果需要,构造函数也可以带有参数。这样在创建对象时就会给对象赋初始值。

例子:

 1 #include <iostream>
 2  
 3 using namespace std;
 4  
 5 class Line
 6 {
 7    public:
 8       void setLength( double len );
 9       double getLength( void );
10       Line(double len);  // 这是构造函数
11  
12    private:
13       double length;
14 };
15  
16 // 成员函数定义,包括构造函数
17 Line::Line( double len)
18 {
19     cout << "Object is being created, length = " << len << endl;
20     length = len;
21 }
22  
23 void Line::setLength( double len )
24 {
25     length = len;
26 }
27  
28 double Line::getLength( void )
29 {
30     return length;
31 }
32 // 程序的主函数
33 int main( )
34 {
35    Line line(10.0);
36  
37    // 获取默认设置的长度
38    cout << "Length of line : " << line.getLength() <<endl;
39    // 再次设置长度
40    line.setLength(6.0); 
41    cout << "Length of line : " << line.getLength() <<endl;
42  
43    return 0;
44 }
View Code

 在C++中,explicit关键字用来修饰类的构造函数,被修饰的构造函数的类,不能发生相应的隐式类型转换,只能以显示的方式进行类型转换。

使用初始化列表来初始化字段:

下面两种写法等价:

Line::Line( double len): length(len)
{
    cout << "Object is being created, length = " << len << endl;
}

Line::Line( double len)
{
    length = len;
    cout << "Object is being created, length = " << len << endl;
}

常见的析构函数:它会在每次删除所创建的对象时执行。析构函数的名称与类的名称是完全相同的,只是在前面加了个波浪号(~)作为前缀,它不会返回任何值,也不能带有任何参数。析构函数有助于在跳出程序(比如关闭文件、释放内存等)前释放资源。

例如:

 1 #include <iostream>
 2  
 3 using namespace std;
 4  
 5 class Line
 6 {
 7    public:
 8       void setLength( double len );
 9       double getLength( void );
10       Line();   // 这是构造函数声明
11       ~Line();  // 这是析构函数声明
12  
13    private:
14       double length;
15 };
16  
17 // 成员函数定义,包括构造函数
18 Line::Line(void)
19 {
20     cout << "Object is being created" << endl;
21 }
22 Line::~Line(void)
23 {
24     cout << "Object is being deleted" << endl;
25 }
26  
27 void Line::setLength( double len )
28 {
29     length = len;
30 }
31  
32 double Line::getLength( void )
33 {
34     return length;
35 }
36 // 程序的主函数
37 int main( )
38 {
39    Line line;
40  
41    // 设置长度
42    line.setLength(6.0); 
43    cout << "Length of line : " << line.getLength() <<endl;
44  
45    return 0;
46 }
View Code

拷贝构造函数:

猜你喜欢

转载自www.cnblogs.com/fanhua666/p/11512850.html