N8_Coder
N8_Coder

Reputation: 803

Call static function in C++

I am writing a code to work with vectors in C++. I've got 3 files: main.cpp, Vektor.cpp and Vektor.h Now I want to call a static funktion in main, which is implemented in Vektor.cpp and declarated in Vektor.h. "test" and "test2" are two instances of the class Vektor. Eclipse throws an Error out, but i do not know why; it says

Multiple markers at this line - Function 'addieren' could not be resolved - 'addieren' was not declared in this scope - Invalid overload of 'endl' - Line breakpoint: main.cpp [line: 28]

Where is the mistake? The "Vektor.h" is included. Here are the necessary cuttings:

main.cpp:

// ...
cout << "Summe: " << addieren(test,test2) << endl;

Vektor.cpp:

Vektor Vektor::addieren(Vektor vektor1, Vektor vektor2)
{
Vektor vektorSumme;
vektorSumme.set_x(vektor1.get_x() + vektor2.get_x());
vektorSumme.set_y(vektor1.get_y() + vektor2.get_y());
vektorSumme.set_z(vektor1.get_z() + vektor2.get_z());
return vektorSumme;
} 

Vektor.h:

class Vektor

{
//...
public:
  //...
static Vektor addieren(Vektor vektor1, Vektor vektor2);

Thanks for helping!!

Upvotes: 1

Views: 2212

Answers (4)

Alok Save
Alok Save

Reputation: 206526

You need to call it as:

Vektor::addieren(test,test2);

static member functions can be called with fully qualified name of the class. They can also be called on a class instance, but since you don't have any instance it doesn't apply here.

Upvotes: 5

4pie0
4pie0

Reputation: 29724

You need to call this with fully qualified name of the class, as:

Vektor v_res=Vektor::addieren(test, test2);

or on an object (instance of class):

Vektor v;
Vektor v_res=v.addieren(test, test2);

Upvotes: 1

Martin Perry
Martin Perry

Reputation: 9527

You should call it

Vektor::addieren(test, test2)

But I would suggest you, to improve addieren function to pass both vectors by reference or pointer.

addieren(Vektor & vektor1, Vektor & vektor2)

or

addieren(Vektor * vektor1, Vektor * vektor2)

but then you must call it with

Vektor::addierent(&test, &test2)

Upvotes: 1

piokuc
piokuc

Reputation: 26184

The syntax for calling static functions is: Vektor::addieren(...)

Upvotes: 1

Related Questions