Wierd Object Issues (C++)

Started by
3 comments, last by elektronjunge 16 years, 5 months ago
Hi I'm having trouble initializing an object of a class within another class. I am try to initialize a map and find information About the map so I can (in the future) setup a route. The person only needs to be able to see what is in each node of the map. Also in the future I will need to create a universal map that places the routes on it. (Please don't try to help me with that, unless your feeling particularly helpful, I just want to get this done for now).

#include <vector>
#include <cassert>
#include <iostream>

struct Node {
	int weight;
	bool isPerson;
	Node(int weight, bool isPerson) : weight(weight), isPerson(isPerson) {}
};


class Map {
	public:
		std::vector<std::vector<Node> > map;
		Map(unsigned int x, unsigned int y) : map(x, std::vector<Node>(y, Node(9, false))) {
			assert(x != 0 && y != 0);
		}
		int getHeight() { return map[0].size(); }
		int getWidth() { return map.size(); }
		int getWeight(int x, int y) { return map[x][y].weight; }
		bool getPerson(int x, int y) {return map[x][y].isPerson; }
		
};

class Person{
public:
	Map myMap (5,5);
	Node start;
	Node end;
	void setStart(int x, int y);
	void setEnd(int x, int y);
};

void Person::setStart(int x, int y){
	start = myMap.map[x][y];
}

void Person::setEnd(int x, int y){
	end = myMap.map[x][y];
}


int main(){
	std::cin.ignore();
}



The Map myMap (5,5); line is of particular problem. Here are the errors from VS: (27) : error C2059: syntax error : 'constant' (35) : error C2228: left of '.map' must have class/struct/union (39) : error C2228: left of '.map' must have class/struct/union
Advertisement
Right. C++ doesn't support that style syntax. Such initialization goes in the constructor if it's constant like that.
You want something like

Person::Person()    :myMap(5, 5){}
class Map {	std::vector<std::vector<Node> > map;	public:	Map(unsigned int x, unsigned int y) : map(x, std::vector<Node>(y, Node(9, false))) {		assert(x != 0 && y != 0);	}	int getHeight() { return map[0].size(); }	int getWidth() { return map.size(); }	Node& at(int x, int y) { return map[x][y]; }	const Node& at(int x, int y) const { return map[x][y]; }	};// Clients can inspect the returned Node as required.// Better yet, use boost::multi_array.class Person {	Map myMap;	// You probably don't want to make copies of the start/end nodes,	// since they'll be out of sync with any changes to the map.	// Actually, you're probably best off tracking the actual position values...	Node* start;	Node* end;public:	Person(int startx, int starty, int endx, int endy) :	myMap(5, 5), start(&myMap.at(startx, starty)), end(&myMap.at(endx, endy)) {}};
Thanks for all the help.

This topic is closed to new replies.

Advertisement