Class / member function error

I have this piece of code here:

class physics_vector
{ 
public:
    double direction, magnitude;
    int dir_mag(double dir, double mag) :direction(dir), 
        magnitude(dir) {return 0; };
};

int dir_mag(double dir, double mag)
{
    cout << "Direction: " << dir << '\n';
    cout << "Magnitude: " << mag << '\n';
    return 0;
}

Whenever I try to compile, I get an error,

13:39: error: only constructors take member initializers

Any help please?

+3
source share
2 answers

This function:

int dir_mag(double dir, double mag) :direction(dir), magnitude(dir)
{return 0; };

uses a list of initializers ( :direction(dir), magnitude(dir)) and allows only constructors. If you were planning on making this a constructor, your class should look like this:

class physics_vector
{ 
public:
    double direction, magnitude;
    physics_vector(double dir, double mag) :direction(dir), 
        magnitude(dir) {};
};

And it will compile. Note that you are not allowed to return a value from the constructor, and they do not have return types.

+4
source

. ++. . .

+1

All Articles