构造和析构

2023/07/28 C++ 共 1511 字,约 5 分钟

构造函数

与类名完全相同的成员函数为这个类的构造函数,构造函数没有返回值.

class A
{
    int i;
    A();
}

A::A(int i)
{
    this.i = i;
};

析构函数

析构函数的命名为在构造函数名前加~,注意析构函数不能有参数.

class A
{
    int i;
    A();
    ~A();
};

A::A(int i)
{
    this.i = i;
};
A::~A()
{
    
}

何时构造和析构

在对象创建时创建调用构造函数,在对象的作用域终结时,析构.

举例:

int main()
{
    {
        A a;        //构造
        a.i = 1;
    }               //析构
}                   //注意:不是在这里析构的!

构造和析构必须成对出现,如果通过goto跳过构造,则编译器会返回error.

class A
{
    int a;
public:
    A(int i);
};

A::A(int i)
{
    a = i;
}

int main(int argc, char const *argv[])
{
    int i = 0;
    if(i < 10)
        goto result;
    A a1(1);
result:
    return 0;
}


编译这段代码:

goto_init

含有继承的父子类构造

  1. 构造子类对象时,会调用父类对象的构造方法,如果子类没有指定,则会尝试调用父类的默认构造方法。
  2. 在析构子类对象时,会先析构子类,再析构父类。
  3. name hiding问题,详见:父类子类

样例

#include <iostream>
using namespace std;

class Father
{
private:
    int f;
public:
    Father();
    Father(int);
    ~Father();
    void printSelf();
    void printSelf(int);
    void setSelf(int a);
};

Father::Father(int af):f(af)
{
    cout << "Father constructed! int" << endl;
}
Father::Father()
{
    cout << "Father constructed! no para" << endl;
}

Father::~Father()
{
    cout << "Father deconstructed!" << endl;
}

void Father::setSelf(int a)
{
    this->f = a;
}

void Father::printSelf(int a)
{
    cout << "Father f=" << this->f << " a=" << a << endl;
}

void Father::printSelf()
{
    cout << "Father f=" << this->f << endl;
}

class Son:public Father
{
private:
    int s;
public:
    Son();
    ~Son();
    void printSelf();
};

Son::Son()
{
    cout << "Son constructed! no para" << endl;
}

Son::~Son()
{
    cout << "Son deconstructed!" << endl;
}


void Son::printSelf()
{
    cout << "Son s=" << this->s << endl;
}

int main(int argc, char const *argv[])
{
    // Father f1(1);
    // f1.printSelf();
    Son s1;
    s1.setSelf(10);
    s1.printSelf();
    s1.Father::printSelf(2);
    return 0;
}

文档信息

Search

    Table of Contents