I've got the following when building a graph.
#include <vector>
using namespace std;
template<class T>
class Node
{
private:
T data;
Node<T> *link;
vector<T> neighbors;
public:
Node(){neighbors = new vector<T>();};
};
int main()
{
Node<int> n;
return 0;
}
... which returns the error C2679: binary '=': no operator found...
I'm using VS2010. What's wrong? Thanks!
The new
operator returns a pointer type, but your member variable neighbors
is not a pointer. So you're assigning a pointer (the result of new
) to a non-pointer type. Your neighbors
variable needs to be a pointer: vector<T>* neighbors
.
But I think you're probably misunderstanding the use of new
here. You probably shouldn't even use a vector pointer at all. Just remove the line neighbors = new vector<T>()
. The vector object will be automatically initialized and ready for use.
In C++, the new
keyword allocates and initializes objects on the heap, which then must be freed later using delete
. It's preferable to avoid the new
keyword by simply initializing the object as an automatic variable, like:
vector<T> neighbors;
This way, you don't have to worry about memory management, and the vector object will automatically be destroyed when it goes out of scope.
vector<T> neighbors;
neighbors = new vector<T>();
neighbours is not a pointer.
The whole point of using vectors is not managing the memory explicitly. In fact in your node constructor, neighbours is default-initialized, so just don't initialize. Your constructor may look like this:
Node(){}
So you can just omit it :)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.