简体   繁体   English

C ++委托构造函数

[英]C++ delegating constructors

Hello i am more familiar with Java than C++ 您好,我比Java更熟悉Java

test.h: test.h:

class Test
{
private:
int a,b,c;
public Test(int a, int b, int c);
}

test.c 测试

Test::Test(int a, int b, int c)
{
this->a = a;
this->b = b;
this->c = c;
}
Test::Test(int a, int b)
{
this(a, b, 0);
}
Test::Test(int a)
{
this(a, 1)
}
Test::Test()
{
this(2)
}

1 - Do i have to type each constructor signature in test.h ? 1-我是否必须在test.h中键入每个构造函数签名?

2 - How can i write multiple definitions of constructors ? 2-如何编写构造函数的多个定义?

3 - I read you can combine multiple constructors in 1 definition using default values. 3-我读到您可以使用默认值在1个定义中组合多个构造函数。 How is that done 怎么做

Thank you 谢谢

  1. Yes

  2. Type them out 输入它们

  3. Why not use Test(int _a, int _b = 1, int _c = 0); 为什么不使用Test(int _a, int _b = 1, int _c = 0);

and define with 定义

Test::Test(int _a, int _b, int _c) : a(_a), b(_b), c(_c)
{
}

ie supply default values and use base member initialisation? 即提供默认值并使用基本成员初始化?

This is also available pre C++11 在C ++ 11之前也可用

as of c++11 one constructor may defer to another. 从c ++ 11开始,一个构造函数可能会推迟到另一个构造函数。 So if you want to avoid publishing the default values in the interface you can do it this way: 因此,如果您要避免在界面中发布默认值,可以采用以下方式:

// declaration
struct X
{
    X(int a, int b, int c);
    X(int a, int b);
    X(int a);
    X();

private:
    int a,b,c;
};

// definition    
X::X(int a, int b, int c)
: a(a), b(b), c(c)
{}


X::X(int a, int b)
: X(a, b, 2)
{
}


X::X(int a)
: X(a, 1, 2)
{
}

X::X()
: X(0,1,2)
{
}

Your constructor delegation syntax is wrong. 您的构造函数委托语法错误。 You need to use the member initialiser list to delegate to a different constructor: 您需要使用成员初始化程序列表来委托给其他构造函数:

Test::Test(int a, int b)
    : Test(a, b, 0)
{
}
Test::Test(int a)
    : Test(a, 1)
{
}
Test::Test()
    : Test(2)
{
}

delegating constructors is only available in C++11. 委托构造函数仅在C ++ 11中可用。 The syntax looks like this: 语法如下所示:

Test::Test(int a1, int b1, int c1) :
    a{a1}, b{b1}, c{c1}
{}

Test::Test(int a, int b) :
    Test(a, b, 0)
{}

Test::Test(int a) :
    Test(a, 1)
{}

Test::Test() :
    Test(2)
{}

I have also used the initialization syntax in the first constructor. 我还在第一个构造函数中使用了初始化语法。 It is preferable to do so, because otherwise the member object will be initialized with the default constructor and then assigned a new value. 最好这样做,因为否则将用默认构造函数初始化成员对象,然后分配一个新值。

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

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