forloRn_
Legacy Member
Iemand een idee waarom dit niet compileert?
De foutmelding:
../src/Entity.cpp: In member function ‘Position& Entity::getPosition() const’:
../src/Entity.cpp:17: error: invalid initialization of reference of type ‘Position&’ from expression of type ‘const Position’
Ik zeg nergens dat het attribuut position constant is, ik zeg enkel dat getPosition() het attribuut position niet zal wijzigen.
Als ik return by constant reference gebruik, compileert het zonder problemen, maar het is wel de bedoeling dat ik de return value kan wijzigen, bijvoorbeeld met getPosition().setX(44).
Entity.h:
Entity.cpp:
Position.h:
De foutmelding:
../src/Entity.cpp: In member function ‘Position& Entity::getPosition() const’:
../src/Entity.cpp:17: error: invalid initialization of reference of type ‘Position&’ from expression of type ‘const Position’
Ik zeg nergens dat het attribuut position constant is, ik zeg enkel dat getPosition() het attribuut position niet zal wijzigen.
Als ik return by constant reference gebruik, compileert het zonder problemen, maar het is wel de bedoeling dat ik de return value kan wijzigen, bijvoorbeeld met getPosition().setX(44).
Entity.h:
Code:
#ifndef ENTITY_H_
#define ENTITY_H_
#include "Position.h"
#include "Vector2D.h"
#include <iostream>
using namespace std;
class Entity {
public:
Entity(const string& newID, int xpos = 0, int ypos = 0, int zpos = 0); // constructors
const string& getID() const; // getters
Position& getPosition() const;
void setPosition(Position& newPosition); // setters
private:
string id;
Position position;
};
#endif /*ENTITY_H_*/
Entity.cpp:
Code:
#include "Entity.h"
#include "Position.h"
#include "Vector2D.h"
#include <iostream>
using namespace std;
Entity::Entity(const string& newID, int xpos, int ypos, int zpos)
:id(newID), position(xpos, ypos, zpos){
}
const string& Entity::getID() const {
return id;
}
Position& Entity::getPosition() const {
return position;
}
void Entity::setPosition(Position& newPosition) {
position = newPosition;
}
Position.h:
Code:
#ifndef POSITION_H_
#define POSITION_H_
class Position {
public:
Position(int x0 = 0, int y0 = 0, int z0 = 0);
int getX() const;
int getY() const;
int getZ() const;
void setX(int x0);
void setY(int y0);
void setZ(int z0);
private:
int x, y, z;
};
#endif /*POSITION_H_*/