I'm refreshing how to write constructors in C++, but the C++ documentation version is throwing silly compiler errors.
I've looked at other examples from stack overflow and mimicked them and still similar errors
assume #includes are already here .h file
class Matrix{
private:
//eventually going to create 2d vector here
public:
// from: http://www.cplusplus.com/doc/tutorial/classes/
Matrix (string);
//another way shown from other examples
Matrix (string filename);
};
.cpp
Matrix::Matrix(string filename){
int num = 0;
string line;
ifstream matrix_file(filename);
if(matrix_file.is_open()){
while(getline(matrix_file, line)){
stringstream extract(line);
while(extract >> num){
cout << num << " ";
}
cout << '\n';
}
matrix_file.close();
}
}
main.cpp
int main(int argc, char *argv[]){
string filename = argv[1];
Matrix grid (filename);
return 0;
}
I'm expecting upon object creation when the constructor is called, it prints out the values in the file. But when compiling, I get:
matrix.h:6:12: warning: unnecessary parentheses in declaration of ‘string’ [-Wparentheses]
Matrix (string);
^
matrix.h:6:19: error: field ‘string’ has incomplete type ‘Matrix’
Matrix (string);
^
matrix.h:2:7: note: definition of ‘class Matrix’ is not complete until the closing brace
class Matrix{
or
matrix.h:6:19: error: expected ‘)’ before ‘filename’
Matrix (string filename);
~ ^~~~~~~~~
)
main.cpp: In function ‘int main(int, char**)’:
main.cpp:11:24: error: no matching function for call to ‘Matrix::Matrix(std::__cxx11::string&)’
Matrix grid (filename);
depending on which way I initialize the string parameter in .h file. I'm thinking I have a small typo somewhere, but I'm not finding anything wrong with this simple piece of code. Any help would be much appreciated. Thanks
assume #includes are already here .h file... seems to be an incorrect assumption. Do you haveusing std?