简体   繁体   中英

Calling constructor with class member, C++

SOLVED: used anonymous class instances:

particle p1(vec(0,0,0),vec(1,0,0),vec(-0.5,0,0),1)

creates the vec instances just to construct the particle instance.

I'm writing a little program for physics and I'm using vectors (in the math sense). The vector looks like

class vec {
public:
    double x, y, z;
    vec() : x(0), y(0), z(0) {}
    vec(double xi, double yi, double zi) : x(xi), y(yi), z(zi) {}
};

so I can create a vector like a(1,0,-1). In a different object, I have

class particle {
public:
    double mass;
    vec pos, vel, acc;
    particle(vec posi, vec veli, vec acci, double m){
        pos = posi; vel = veli; acc = acci; mass = m;
    }
};

I'm not sure how to construct an instance of the particle class. I tried

particle p1((0,0,0),(1,0,0),(-0.5,0,0),1);

but I get an error: no known conversion from double to vec.

You can always call an constructor. You just call it like this class_name(parameters, ...)

In your specific case it would look like this:

particle p1(vec(0, 0, 0), vec(1, 0, 0), vec(-0.5, 0, 0), 1);

What's happening is that you're in fact calling the comma operator. Here is a quick example :

cout << (0, 1, 2) << endl;

prints 2. There are plenty of questions on the subject.

One solution is indeed to use particle p1(vec(0,0,0),vec(1,0,0),vec(-0.5,0,0),1) and create anonymous object.

An alternative syntax was introduced in C++11 that consists in using curly braces like this:

particle p1({0,0,0}, {1,0,0}, {-0.5,0,0}, 1)

It's exactly the same thing but less verbose.

You appear to have misplaced a parenthesis, a variable declaration, a parameter, and some instantiations.

Try:

particle p1 = new particle(new vec(0,0,0),new vec(1,0,0),new vec(-0.5,0,0),0);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM