amazzzzzing

导航

默认函数

默认函数

关于

当用户没有定义时,C++ 会为类对象自动生成一些成员函数,这些函数称为默认函数。

默认函数包括(仅列举重要的默认函数):

  • 默认构造、拷贝构造、移动构造、析构
  • 拷贝赋值
  • 移动赋值

其形式如:

class Obj
{
public:
    Obj();
    Obj(const Obj&);
    Obj(Obj &&);
    ~Obj();
    Obj& operator=(const Obj&);
    Obj& operator=(Obj &&);
};

默认函数的屏蔽

  1. 如果用户定义了默认函数,则不会自动生成。但是如果两者形成了重载关系会如何?

如下:

#include <stdio.h>
class Obj
{
public:
    // Obj& operator=(const Obj&);
    Obj& operator=(Obj&)
    {
        printf ("custom copy operator\n");
        return *this;
    }
};

int main()
{
    Obj obj;
    const Obj cobj;
    Obj test;

    test = obj;
    test = cobj;

    return 0;
}

上述代码尝试调用类的常引用拷贝赋值函数,实际只定义了非常引用拷贝赋值函数。上述代码编译不通过:

g++ test.cpp
test.cpp: In function ‘int main()’:
test.cpp:20:12: error: binding reference of type ‘Obj&’ to ‘const Obj’ discards qualifiers
   20 |     test = cobj;
      |            ^~~~
test.cpp:6:20: note:   initializing argument 1 of ‘Obj& Obj::operator=(Obj&)’
    6 |     Obj& operator=(Obj&)
      |

因此有结论:只要定义了一个函数,则构成重载的同一类函数均不会自动生成。

posted on 2023-06-02 01:34  amazzzzzing  阅读(56)  评论(0)    收藏  举报