C ++,用它来自己调用构造函数

时间:2011-09-14 20:33:45

标签: java c++ this

我昨晚写了一些java,我有两个看起来基本相似的构造函数,除了我的默认构造函数为我的对象提供了一些值,它是这样的:

testObject(){
     width=5;
     height=12;
     depth=7;
     //other stuff is the same as the next one
}

testObject(int x, int y, int z){
    width=x; 
    height = y;
    depth = z;
    //All the other stuff is the same as default
}

所以在这种情况下,我能够转换代码来代替:

testObject(){
    this(5,12,7);
}

它将默认构造函数中的值作为要构建的3-int构造函数发送回构造函数。有没有办法在C ++中获得这种类型的功能?

6 个答案:

答案 0 :(得分:5)

在C ++ 0x中,你可以这样做:

TestObject() :TestObject{5, 12, 7} {}

有关详细信息,请参阅Delegating Constructors。 (你不太熟悉大括号吗?他们是preventing narrowing。)

如果您还没有可用的C ++ 0x,那么在您的情况下,您可以使用其他答案中提到的默认参数。

答案 1 :(得分:1)

你很接近,尝试在你的默认构造函数的初始化列表中调用3参数构造函数。

testObject(int x, int y, int z) :
    width(x), 
    height(y),
    depth(z) {
    //All the other stuff is the same as default
}

testObject() : testObject(5,12,7) {
     //other stuff is the same as the next one
}

答案 2 :(得分:0)

没有办法做到这一点,但您可以使用初始化代码创建一个私有方法,并从不同的构造函数中调用它。

编辑:Can I call a constructor from another constructor (do constructor chaining) in C++?

的副本

答案 3 :(得分:0)

您可以在构造函数中使用默认值(即testObject(int x = 5,int y = 12,int z = 7))来执行您想要的操作。

答案 4 :(得分:0)

最有趣的是你不需要这样做。默认参数旨在解决此类问题。这是一个例子:

#include <iostream>

struct Foo
{
    int x, y, z;

    Foo (int x = 5, int y = 12, int z = 7)
        : x (x), y (y), z (z)
    {}
};

int
main ()
{
    Foo f1, f2 (1, 2, 3);
    std::cout << f1.x << ", " << f1.y << ", " << f1.z << '\n'
         << f2.x << ", " << f2.y << ", " << f2.z << '\n';
}

例如,您可以使用placement new来调用类的构造函数,如下所示:

struct Foo
{
    int x, y, z;

    Foo (int x, int y, int z)
        : x (x), y (y), z (z)
    {}

    Foo ()
    {
        this->~Foo ();
        new (this) Foo (5, 12, 7);
    }
};

此功能在C ++ 11中也是开箱即用的,您可以阅读更多here

答案 5 :(得分:0)

您可以将默认变量值添加到您的班级。

testObject::testObject(int x, int y, int z = 5)

然后你可以用它来调用它 testObject(1,2)和z将检索默认值5

相关问题