简体   繁体   English

为什么复制构造函数会隐藏C ++中的默认构造函数?

[英]Why does copy constructor hide the default constructor in C++?

#include <iostream>
#include <conio.h>

using namespace std;

class Base
{
      int a;
public:
      Base(const Base & b)
      {
                 cout<<"inside constructor"<<endl;
      }   

};

int main()
{
   Base b1;
   getch();
   return 0;
}

This gives an error. 这给出了一个错误。 no matching function for call to `Base::Base()' Why? 没有匹配函数来调用`Base :: Base()'为什么?

The default constructor is only generated if you don't declare any constructors. 仅当您未声明任何构造函数时,才会生成默认构造函数。 It's assumed that if you're defining a constructor of your own, then you can also decide whether you want a no-args constructor, and if so define that too. 假设你定义了自己的构造函数,那么你也可以决定是否需要一个无参数的构造函数,如果是这样的话,也可以定义它。

In C++0x, there will be an explicit syntax for saying you want the default constructor: 在C ++ 0x中,会有一个明确的语法来表示你想要默认的构造函数:

struct Foo {
    Foo() = default;
    ... other constructors ...
};

It does not hide the default constructor, but declaring any constructor in your class inhibits the compiler from generating a default constructor, where any includes the copy constructor. 它不会隐藏默认构造函数,但声明类中的任何构造函数会禁止编译器生成默认构造函数,其中any包含复制构造函数。

The rationale for inhibiting the generation of the default constructor if any other constructor is present is based on the assumption that if you need special initialization in one case, the implicitly generated default constructor is most probably inappropriate. 如果存在任何其他构造函数,则禁止生成默认构造函数的基本原理基于以下假设:如果在一种情况下需要特殊初始化,则隐式生成的默认构造函数很可能是不合适的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM