C++类默认有哪些函数

2021/6/2 12:21:14

本文主要是介绍C++类默认有哪些函数,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

         例如下面一个空类Test,没有任何代码

class Test{

};

一 空类的大小

        在main方法中计算Test空类的大小,

int main() {
    cout << "空类大小是 : " << sizeof(Test) << endl;
    return 0;
}

        输出结果:空类大小是 : 1

        为什么不是0,Test类里什么都没有。

        大概需要这样理解吧,每个对象在内存中都有地址,编译时,编译器会给空类隐含的加一个字节,所有空类的大小是1.

 

二 空类的默认函数

         下面来看看空类是否可以构造对象,进行了下面的操作,发现都没问题

    Test t;

    Test t1 = t;

    Test t2;
    t2 = t;

    Test *t3 = &t;

    const Test *t4 = &t;

        那说明空类至少有如下函数:(1)默认构造函数,(2)拷贝构造函数,(3)重载了赋值操作符,(4)取地址符,(5)常对象取地址符;(6)析构函数。

        把这些函数补全看看。

    Test(int value = 0):m_Value(value)
    {
        cout << "这是构造函数 ";
        cout << "m_Value = " << m_Value << endl;
    }

    Test(const Test& t)
    {
        cout << "这是拷贝构造函数" << endl;
        m_Value = t.m_Value;
    }

    Test& operator=(const Test &t)
    {
        if(this!=&t)
        {
            m_Value = t.m_Value;
        }

        cout << "赋值操作符" << endl;
        return *this;
    }

    Test*operator&()
    {
        cout << "取址操作" << endl;
        return this;
    }

    const Test*operator&() const
    {
        cout << "常对象取址操作" << endl;
        return this;
    }

    ~Test()
    {
        cout << "这是析构函数" << endl;
    }

        测试结果:

这是构造函数 m_Value = 0
这是拷贝构造函数
这是构造函数 m_Value = 0
常对象取址操作
赋值操作符
取址操作
取址操作
这是析构函数
这是析构函数
这是析构函数

       析构了3次,说明有3个对象t, t1, t2, 他们在程序结束时要析构,t3, t4只是取址。

       本例子代码如下:

#includeusing namespace std;

class Test 
{
public:
    Test(int value = 0) :m_Value(value)
    {
        cout << "这是构造函数 ";
        cout << "m_Value = " << m_Value << endl;
    }

    Test(const Test& t)
    {
        cout << "这是拷贝构造函数" << endl;
        m_Value = t.m_Value;
    }

    Test& operator=(const Test& t)
    {
        if (this != &t)
        {
            m_Value = t.m_Value;
        }

        cout << "赋值操作符" << endl;
        return *this;
    }

    Test* operator&()
    {
        cout << "取址操作" << endl;
        return this;
    }

    const Test* operator&() const
    {
        cout << "常对象取址操作" << endl;
        return this;
    }

    ~Test()
    {
        cout << this << endl;
        cout << "这是析构函数" << endl;
    }

private:
    int m_Value;
};


int main() {
    //cout << "空类大小是 : " << sizeof(Test) << endl;

    Test t;
    cout << "t 地址 = " << &t << endl;

    Test t1 = t;
    cout << "t1 地址 = " << &t1 << endl;

    Test t2;
    t2 = t;
    cout << "t2 地址 = " << &t2 << endl;

    Test* t3 = &t;
    cout << "t3 地址 = " << &t3 << endl;

    const Test* t4 = &t;
    cout << "t4 地址 = " << &t4 << endl;

    return 0;
}

运行结果:

这是构造函数 m_Value = 0
t 地址 = 取址操作
0075F9FC
这是拷贝构造函数
t1 地址 = 取址操作
0075F9F0
这是构造函数 m_Value = 0
常对象取址操作
赋值操作符
t2 地址 = 取址操作
0075F9E4
取址操作
t3 地址 = 0075F9D8
取址操作
t4 地址 = 0075F9CC
0075F9E4
这是析构函数
0075F9F0
这是析构函数
0075F9FC
这是析构函数

后构造的先析构,这是栈,先入栈的后出栈,后入栈的先出栈。



这篇关于C++类默认有哪些函数的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程