Call to non-static member function without an object argument compiler error
The error message from the compiler is very clear.
getInput
is a non-static
member function of the class.
You need an object of the class to be able to use that member function.
Instead of
stats::getInput(std::cin);
use
stats obj;
obj.getInput(std::cin);
Another solution.
Since the class does not have any member variables, you may change getInput
to a static
member functions.
class stats {
public:
stats();
static std::vector <double> getInput(std::istream& input_stream);
private:
};
If you do that, you may use:
stats::getInput(std::cin);
Also, your loop to read the data can be simplified to:
while (input_stream >> x){
stream.push_back(x);
}
Brock Morrison
Updated on September 11, 2020Comments
-
Brock Morrison over 3 years
I am working on a project for my intro to c++ class which is to build a program to calculate various statistics. I have the calculations down, but our professor wants us to use
std::istream
to collect the input from a file. The program will keep collecting information from the file until it reaches an End of File marker. I am very unfamiliar with the waystd::istream
works and I keep encountering this error when I try to compile.main.cpp:5:10: error: call to non-static member function without an object argument stats::getInput(std::cin);
Here is my stats.cpp file:
#include "stats.h" #include <vector> #include <cstdlib> #include <iostream> stats::stats(){ } std::vector <double> stats::getInput(std::istream& input_stream){ std::vector <double> stream; double x; while(input_stream){ input_stream >> x; // std::cout << "your list of numbers is: " << x << std::endl; if(input_stream){ stream.push_back(x); } } return stream; }
Here is my header file:
#ifndef _STATS_ #define _STATS_ #include <vector> #include <cstdlib> class stats{ public: stats(); std::vector <double> getInput(std::istream& input_stream); private: }; #endif
and here is my main.cpp file:
#include "stats.h" #include <iostream> int main(){ stats::getInput(std::cin); }
Like I said, I am a beginner in c++ so the answer is probably fairly simple, but c++ is vastly different than Python. I have seen similar questions, but none of them have helped me figure it out.
Thanks