《新标准C++程序设计》3.1.4-3.2(C++学习笔记6)

1、类型转换构造函数

(1)定义

只有一个参数,而且不是复制构造函数的构造函数,一般就可以看作是转换构造函数。

当需要的时候,编译系统会自动调用转换构造函数,建立一个无名的临时对象(或临时变量)。

(2)作用:实现类型的自动转换

程序示例分析:

#include<iostream>
using namespace std;
class Complex {
public:
    double real, imag;
    Complex(int i)//类型转换构造函数
    {
        cout << "IntConstructor called" << endl;
        real = i;
        imag = 0;
    }
    Complex(double r, double i)
    {
        real = r;
        imag = i;
    }
};
int main()
{
    Complex c1(7, 8);
    Complex c2 = 12;
    c1 = 9;//9被自动转换成一个临时Complex对象
    cout << c1.real << "," << c1.imag << endl;
    return 0;
}

输出结果:

IntConstructor called
IntConstructor called
90

2、析构函数

(1)什么是析构函数

名字与类名相同,在前面加‘~’ ,没有参数和返回值,一 个类最多只能有一个析构函数。

析构函数对象消亡时即自动被调用。可以定义析构函数来在对象消亡前做善后工作,比如释放分配的空间等。

如果定义类时没写析构函数,则编译器生成缺省析构函数。缺省析构函数什么也不做。

如果定义了析构函数,则编译器不生成缺省析构函数。

class String {
private:
    char* p;
public:
    String(int n);
    ~String();
};
String::~String()
{
    delete[]p;
}
String::String(int n)
{
    p = new char[n];
}

(2)析构函数和数组

对象数组生命期结束时,对象数组的每个元素的析构函数都会被调用。

class Ctest {
public:
    ~Ctest() { cout << "destructor called" << endl; }
};
int main() {
    Ctest array[2];
    cout << "End Main" << endl;
    return 0;
}

输出结果:

End Main
destructor called
destructor called

(3)析构函数和运算符delete

delete 运算导致析构函数调用。

Ctest* pTest;
pTest = new Ctest;     //构造函数调用
delete pTest;          //析构函数调用
-------------------------------------------------------- -
pTest = new Ctest[3];  //构造函数调用3次
delete[] pTest;        //析构函数调用3次

若new一个对象数组,那么用delete释放时应该写 [ ]。否则只delete一个对 象(调用一次析构函数)

(4)析构函数在对象作为函数返回值返回后被调用

class CMyclass {
public:
    ~CMyclass() { cout << "destructor" << endl; }
};
CMyclass obj;                  //整个程序结束后消亡
CMyclass fun(CMyclass sobj) { //参数对象消亡也会导致析构函数被调用
    return sobj;              //函数调用返回时生成临时对象返回
}
int main() {
    obj = fun(obj);           //函数调用的返回值(临时对象)被用过后,该临时对象析构函数被调用
    return 0; 
}

输出结果:

destructor
destructor
destructor
原文地址:https://www.cnblogs.com/cyn522/p/12252331.html