Reputation: 611
I have a header file where i am declaring a class with a structure within it. Also i am declaring an overloading operator(!=, to compare structures) as member of this class. I am giving the definition of this operator in the cpp file. But i am not able to access the members of the structure
car.h
class car
{
int carsor;
struct model
{
int id;
int mode;
}prev,curr;
bool operator !=(const model& model1);
};
car.cpp
#include "car.h"
bool car::operator !=(const model& model1)
{
if((model1.id==model.id)&&(model1.mode==model.mode))
{
return false;
}
else
{
return false;
}
}
The error i get is this
Error 2 error C2275: 'car::model' : illegal use of this type as an expression
how should i access the the structure members?
Upvotes: 0
Views: 284
Reputation: 67772
This:
bool car::operator !=(const model& model1)
{
is a method comparing a car to a model. This, however:
bool car::model::operator != (car::model const &other) const
{
return !(*this == other);
}
is a method comparing two models (I've written it here as a method of car::model
, but it could be a free function if you prefer.
I've also written it in terms of operator==
, because the logic almost always works out easier:
bool car::model::operator ==(car::model const &other) const
{
return (this->id == other.id) && (this->mode == other.mode);
}
These methods would be declared as:
class car
{
struct model
{
int id;
int mode;
bool operator==(model const&) const;
bool operator!=(model const&) const;
// ...
Upvotes: 0
Reputation: 18368
if((model1.id==model.id)&&(model1.mode==model.mode))
- model
is the name of your class and not your object. Your object is accessible via this
or you may omit it altogether inside the class.
Use if((model1.id==prev.id)&&(model1.mode==prev.mode))
to compare with prev
or if((model1.id==next.id)&&(model1.mode==next.mode))
to compare with next.
Upvotes: 3