使用C ++构造函数的不同方法 [英] Different ways of using C++ constructors

查看:107
本文介绍了使用C ++构造函数的不同方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

A a1(5); A a2 = A(5)?这两个作品,但我真的想知道他们之间的区别,因为我使用方法2在我的项目之一,我遭受一个错误,是固定的,在我改变方法1之后。提前感谢!

What the difference between A a1(5); and A a2 = A(5) ? Both of the works, but I really want know the difference between them, because I used method 2 in one of my project and I suffered from a bug which is fixed after I change to method 1. Thanks in advance!

class A {
public:
    int val;
    A() : val(0) {}
    A(int newVal) : val(newVal) {}
};

int main()
{
    A a1(5);  // method 1
    A a2 = A(5); // method 2
}


推荐答案

A a1(5);  // method 1
A a2 = A(5); // method 2

第一个称为直接初始化,第二个称为复制初始化。

The first one is called direct initialization, the second one is called copy-initialization.

如果您使复制构造函数无法访问或/和不将其定义为第二个将不会编译:

The second one will NOT compile if you make the copy-constructor inaccessible or/and don't define it as:

class A {
public:
    int val;
    A() : val(0) {}
    A(int newVal) : val(newVal) {}
private:
    A(A const&);  //the second one will not compile
};

现在第二个不能编译。请注意,在这两种情况下都不会编译:

Now the second one will not compile. Note that it will not compile in both cases:


  • 如果定义了复制构造函数,但不可访问$ c> private 或 protected )。

  • 如果复制构造函数已声明。

  • If the copy-constructor is defined, but is inaccessible (either it is private or protected).
  • If the copy-constructor is declared, but not defined.

这篇关于使用C ++构造函数的不同方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆