开发者

C++, using this to call a constructor from itself

I was writing some java last night and I had t开发者_如何转开发wo constructors that looked basically alike, except my default constructor provided some values to my object, it was something like this:

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
}

So in this case, I was able to convert the code to do this instead:

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

That sent the values from the default constructor back to the constructor as the 3-int constructor to be built as such. Is there any way to get this type of functionality in C++?


In C++0x, you can do this:

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

See Delegating Constructors for more details. (Curly braces not look familiar to you? They're for preventing narrowing.)

If you don't have C++0x available yet, then in your case, you can use default arguments as mentioned in other answers here.


You were close, try calling the 3-parameter constructor in your initializer list for your default constructor.

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
}


There is no way to do this, but you can create a private method with initialization code and call it from your different constructors.

EDIT: duplicate of Can I call a constructor from another constructor (do constructor chaining) in C++?


You can use default values in the constructor (i.e. testObject(int x = 5, int y = 12, int z = 7) ) to do what you want.


The most interesting thing is that you don't need to do that. Default arguments are aimed at solving problems like this. Here is an example:

#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';
}

Just for example sake, you can call a constructor of a class using placement new, like this:

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);
    }
};

This feature also comes out of the box in C++11, you can read more here.


You can add default variable values to your class.

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

Then you can call it with testObject(1,2) and z will retrieve the default value of 5

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜