Reputation: 1945
I want to add some values to a vector in my c++ code but every time I try and send the vector to the function in my main.cpp file it underlines it in red and say:
A nonstatic member reference mus be relative to a specific object.
In my Header:
#ifndef HEADER_H
#define HEADER_H
#include <vector>
namespace Functions{
class MyClass
{
public:
void fun(std::vector<char*> vect);
};
}
#endif
.cpp file:
void Functions::MyClass::fun(std::vector<char*> vect){
vect.push_back("value 1");
vect.push_back("Save File Name");
}
Main.cpp
#include "Header.h"
#include <vector>
int main(){
std::vector<char*>vect;
Functions::MyClass::fun(vect);
return 0;
}
Upvotes: 0
Views: 2780
Reputation: 126552
You are calling your fun()
member function as if it were a static function. Since it is a regular member function instead, you should create an object on which to invoke it:
Functions::MyClass m;
m.fun(vect);
If your function does not need to work on any concrete instance of the class it is a member of, you can declare it as static
. That would allow you to call it the way you are currently calling it.
Besides, as others have pointed out already, it is probably a good idea to pass the vector by reference:
void fun(std::vector<char*>& vect)
// ^
Passing by value will create a copy of the argument in vect
, meaning that the calling function will not see any side-effect after the call to fun()
.
Also, a good idea is to use std::string
rather than pointers to char
(especially if not const
):
#include <string> // Requires for std::string
// ...
void Functions::MyClass::fun(std::vector<std::string>& vect)
// ^^^^^^^^^^^
{
vect.push_back("value 1");
vect.push_back("Save File Name");
}
Upvotes: 10
Reputation: 71009
You have two problems:
You are calling a non-static function without an object. To fix that declare an object of type MyClass and call fun
on it:
int main(){
Functions::MyClass a;
std::vector<char*>vect;
a.fun(vect);
return 0;
}
You only modify a local copy of vect
in your function. To fix that pass the vector by reference to the function:
void Functions::MyClass::fun(std::vector<char*>& vect){
vect.push_back("value 1");
vect.push_back("Save File Name");
}
Of course declaration should also be changed accordingly.
Upvotes: 4