Reputation: 53
I am trying to make a static vector of a class (called "radsurf") so when a instance is constructed it will be appended to the vector.
But I have had some issues when compiling the code using g++.
It tells me there is "no matching function for call" for the static vector of the class.
Can someone help me?
Tree View:
├── include
│ └── radsurf.h
└── radiacaoapp.cpp
radiacaoapp.cpp:
#include <iostream>
#include <vector>
#include "include/radsurf.h"
using namespace std;
int main(){
radsurf a(0.1); // creates one instance
radsurf b(0.5); // creates another instance
// read the list of "e" parameters of the radsurf instances
for (radsurf x : radsurf::L) {
cout << x.e << endl;
}
return 0;
}
radsurf.h:
#ifndef RADSURF_H
#define RADSURF_H
#include <vector>
class radsurf{
public:
// "e" parameter - each instance has its own
float e;
// L vector that contains all instances of radsurf classes
static std::vector<radsurf> L;
radsurf(float e){
// assign constructor argument to the "e" parameter of the instance
this->e=e;
// adds the instance to the list
L.push_back(this);
}
};
#endif // RADSURF_H
Error of g++ compiler:
[chandler@chandler-PC radiacaoapptest]$ g++ radiacaoapp.cpp -o test.bin
In file included from radiacaoapp.cpp:3:
include/radsurf.h: In constructor ‘radsurf::radsurf(float)’:
include/radsurf.h:15:33: error: no matching function for call to ‘std::vector<radsurf>::push_back(radsurf*)’
15 | L.push_back(this);
| ^
Upvotes: 0
Views: 683
Reputation: 91
In C++, the this
keyword is a pointer to the current object instance. Your std::vector<radsurf>
is a vector of radsurf
objects, not pointers to radsurf
objects (not radsurf*
s).
The static vector should instead by a std::vector<radsurf*>
, meaning it contains a list of radsurf pointers. If you instead want a vector of values (which I doubt), then you can instead L.push_back(*this);
to dereference this
before copying it in.
Upvotes: 3