美文网首页C++C++
C++中编译器默默生成的函数

C++中编译器默默生成的函数

作者: Kai_Z | 来源:发表于2018-03-21 23:04 被阅读18次

    简介

    本章主要用于介绍当我们在定义一个的时候,编译器会默默的帮我们生成哪些函数。
    在阅读本章之前,强烈建议先阅读C++中的构造函数

    构造函数生成规则

    当一个不包含任何构造函数的类被定义的时候,编译器会默默的为它声明默认构造函数copy构造函数copy赋值运算符移动构造函数移动赋值运算符。当然这些函数只有在被调用的时候,才会被编译器创造出来。

    在生成的copy构造函数copy赋值运算符中,所作的事情就是将类中的成员变量进行复制

    例程

    #include "stdafx.h"
    #include <iostream>
    
    class Test {
    public:
        int value = 10;
    };
    /*
    //类似于写了如下代码
    class Test{
    public:
        Test():value(10){}
        Test(const Test& t)
        {
              value = t.value;
        }
        Test& operator=(const Test& t)
         {
              value = t.value;
              return *this;
         }
    
    };
    */
    int main()
    {
        Test test; // default constructor
        std::cout <<"test.value: " <<test.value << std::endl;
        test.value = 100;
        Test test2(test); // copy constructor
        std::cout <<"test2.value: " <<test2.value << std::endl;
        test2.value = 300;
        test = test2; // copy assignment
        std::cout <<"test.value: " <<test.value << std::endl;
        return 0;
    }
    //输出结果
    test.value: 10
    test2.value: 100
    test.value: 300
    

    从以上代码中,可以看出编译器为Test类生成了默认构造函数,copy构造函数以及copy赋值运算符,所以我们可以调用

    Test test2(test); // copy constructor
    test = test2; // copy assignment
    

    需要注意的地方

    • 并不是所有的,编译器都可以默默生成copy构造函数copy赋值运算符,例如:当类中包含成员变量是不支持copy的时候,编译器会拒绝生成copy构造函数copy赋值运算符

    下一章内容:C++中如何禁止编译器生成构造函数

    相关文章

      网友评论

        本文标题:C++中编译器默默生成的函数

        本文链接:https://www.haomeiwen.com/subject/pgyuqftx.html