I have a struct Point, which has a constructor with parameters and a class called Circle.
struct Point{
int x, y;
Point(){}
Point(int ox, int oy) : x(ox),y(oy){}
};
class Circle{
public:
Point obj;
int radius;
Circle(Point pt(int ox, int oy), int raza) : obj.x(ox), obj.y(oy), radius(raza) {}
};
int main()
{
Circle(Point p(2,3),3);
return 0;
}
The problem is that I don't know how to pass a struct constructor with parameters as parameter to my Circle class constructor.
CodePudding user response:
Circle(Point pt(int ox, int oy), int raza) : obj.x(ox), obj.y(oy), radius(raza) {}
is wrong syntax and should simply be:
Circle(Point pt, int raza) : obj(pt), radius(raza) {}
And then
Circle circle(Point(2, 3), 3);
CodePudding user response:
You can do that like this :
class Point
{
public:
Point(int x, int y) :
m_x(x),
m_y(y)
{
}
private:
int m_x{ 0 };
int m_y{ 0 };
};
class Circle
{
public:
Circle(const Point& pt, int raza) :
m_point{ pt },
m_radius{ raza }
{
}
private:
Point m_point;
int m_radius;
};
int main()
{
Circle c1(Point(2,3), 3);
// or use this shorter variant.
// first parameter is a Point, {2,3} looks for a constructor
// of Point with two ints of point and finds it.
Circle c2({ 2,3 }, 3);
return 0;
}
CodePudding user response:
What you intended could be done in the following ways
Circle(int ox, int oy, int raza) :
obj(ox, oy)
radius(raza)
{}
Or
Circle(Point const& pt, int raza) :
obj(pt), //note, here is the implicitly defined copy-constructor of obj called, not the one you defined
radius(raza)
{}
So If you define either of the constructors above the following will be valid
Circle crl(1,2,3); //valid for the first constructor
Circle crl(Point(1,2),3); //valid for the second constructor
Circle crl({1, 2}, 3); //valid for the second constructor