C++ this in constructor? [duplicate]
Possible Duplicate:
c++ call constructor from constructor
How to do "self" (this) assignments in c++?
Java:
public Point(Point p) {
this(p.x, p.y);
}
How would do this in C++?
Would it be similar only this->(constructor of point that takes x, constructor of point that takes y);
?
In C++0x, you can use delegating constructors:
Point(const Point &p) : Point(p.x, p.y) { }
Note that no compiler has full support for C++0x yet; this particular feature is not yet implemented in G++.
In older versions of C++, you have to delegate to a private construction function:
private:
void init(int x, int y) { ... }
public:
Point(const Point &p) { init(p.x, p.y); }
Point(int x, int y) { init(x, y); }
If I understand what you mean by this Java code (a constructor that relies on another constructor of the same class to do the job):
public Point(Point p) {
this(p.x, p.y);
}
this is how I would express the same in C++:
class Point {
Point(const Point& p)
: Point(p.x, p.y)
{
...
}
};
If you call another constructor of the same class it will create a new object.
If you want to do this, you should put the constructor logic in an init method and call it from all constructors.
精彩评论