在课堂内使用运算符过载
Use of operator overloading in structure within class
我有一个标头文件,我在其中宣布其中包含结构的类。另外,我还声明了一个超载操作员(!=,将结构)作为此类的成员。我在CPP文件中给出了该操作员的定义。但是我无法访问结构的成员
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;
}
}
我遇到的错误是这个
Error 2 error C2275: 'car::model' : illegal use of this type as an expression
我应该如何访问结构成员?
if((model1.id==model.id)&&(model1.mode==model.mode))
- model
是您类的名称,而不是对象的名称。您的对象可以通过this
访问,或者您可以在同类中完全省略它。使用if((model1.id==prev.id)&&(model1.mode==prev.mode))
与prev
或if((model1.id==next.id)&&(model1.mode==next.mode))
进行比较以与Next进行比较。
this:
bool car::operator !=(const model& model1)
{
是将汽车与模型进行比较的方法。但是,这是:
bool car::model::operator != (car::model const &other) const
{
return !(*this == other);
}
是一种比较两个模型的方法(我在这里写了它是car::model
的方法,但是如果您愿意,它可能是一个免费的功能。
我还用operator==
来写它,因为逻辑几乎总是更容易出现:
bool car::model::operator ==(car::model const &other) const
{
return (this->id == other.id) && (this->mode == other.mode);
}
这些方法将被声明为:
class car
{
struct model
{
int id;
int mode;
bool operator==(model const&) const;
bool operator!=(model const&) const;
// ...
相关文章:
- 为什么比较运算符如此快速
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 使用C++中的模板和运算符重载执行矩阵运算
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 增量运算符与后缀混淆
- 一个关于在C++中重载布尔运算符的问题
- 运算符C++ "delete []"仅删除 2 个前值
- 模板类无法识别友元运算符
- 我可以使用条件运算符初始化C风格的字符串文字吗
- 关闭||运算符优化
- 通过继承类使用来自不同命名空间的运算符
- C++Cast运算符过载
- 如何使用AngelScript注册SFML Vector2运算符
- 重载元组索引运算符-C++
- 如何使用重载的相等(==)运算符向测试用例添加描述
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- 布尔比较运算符是如何在C++中工作的
- 重载运算符new[]的行为取决于析构函数
- 在课堂内使用运算符过载