ThomasS
ThomasS

Reputation: 715

access header variable in cpp

Hi I just started programming in C++ and have a problem accessing the variables from the header file in my cpp file.

In my header (Vector.h) I have

class Vector {

public:

    double x, y, z;
Vector cross(const Vector & v);
}

my cpp file (Vector.cpp)

#include "Vector.h"

Vector cross(const Vector & v){
    double x2 = y*v.z-z*v.y;
    double y2 = -x*v.z+z*v.x;
    double z2 = x*v.y-y*v.x;

    return Vector(x2, y2, z2);
}

This gives a Symbol 'x' could not be resolved error (same for y and z). How to I tell the x,y,z are the variables from the header file?

Upvotes: 1

Views: 3075

Answers (2)

Stefan
Stefan

Reputation: 2613

The error tries to tell you that there is no possibility to know what 'x' is and how to resolve it.

Your method needs to have a the class scope in your declaration:

Vector Vector::cross(const Vector & v) {

}

where Vector:: declares the scope.

Upvotes: 1

Cory Kramer
Cory Kramer

Reputation: 118011

You need to declare your function in the class scope

Vector Vector::cross(const Vector & v){
       ^
}

This means that cross is a class method, and therefore has an implicit this to access the member variables x, y, and z in your case.

Upvotes: 5

Related Questions