Home > Mobile >  How to make a class variable in one line?
How to make a class variable in one line?

Time:11-19

In C how make a class variable in one line? For example: I have a class:

class point{
public:
 int x;
 int y;
};

How to make a variable in one line like java you can do new point(x, y), currently I do make a tmp and then push back to vector or something, are the simply way like java can do what I do in one line?

CodePudding user response:

For creating a variable of type point on the stack you can use:

point myVariable{5,6};//this creates a point type variable on stack with x=5 and y=6;

So the complete program would look like:

#include <iostream>
class point{
    public:
        int x;
        int y;
};

int main()
{
    point myVariable{5,6};

    return 0;
}

The output of the above program can be seen here. If you want to create a vector of point objects and then add objects into it, then you can use:

//create point objects
point p1{5,6};
point p2{7,8};

//create a vector
std::vector<point> myVector;

//add p1 and p2 into the vector
myVector.push_back(p1);
myVector.push_back(p2);

CodePudding user response:

Build a constructor Point(int x, int y) : x(x), y(y) {} And then push to vector as usual vec.push_back(Point(x,y))

  •  Tags:  
  • c
  • Related