运算符定义不能正常工作
operator definition not working right
我试图实现一个比较运算符,但我得到以下错误
whole.cpp(384):错误C2270: '==':非成员函数不允许修饰符
whole.cpp(384):错误C2805:二进制'operator =='参数太少
whole.cpp(384):错误C2274: 'function-style cast':非法的'。"操作符
我似乎无法确定问题所在,所以这里是代码
这是类
中的操作符实现bool operator==(const DateC& p) const
{
return ( DateC::DateC()== p.DateC() );
};
#include <assert.h>
int main(unsigned int argc, char* argv[])
{
DateC f(29,33,11);
DateC::testAdvancesWrap();
};
void DateC::testAdvancesWrap(void)
{
DateC d;
cout << "DateC::testAdvanceWrap()" << endl ;
cout << "*********************" << endl << endl ;
cout << "tCHECK ADVANCE MULTIPLES:" << endl;
cout << "t------------------------" << endl;
d.setDay(1);
d.setMonth(12);
d.setYear(1999);
prettyPrint(d);
cout << "ACTION: set date 01-Dec-1999, advance, 31 days, 1 month and 1 year ->" << endl;
d.advance(1,1,31);
assert( d == DateC(1,2,2001) );
cout << "SUCCESS" << endl;
prettyPrint(d);
cout << endl << endl;
}
其他的函数工作得很好,只有assert()
可以将比较运算符实现为成员函数或自由函数。为了实现它作为一个自由函数,你需要接受两个参数——左边的=
的值和右边的=
的值。下面的例子展示了如何正确地做到这一点。
struct Date
{
int variable_;
};
bool operator==(const Date& lhs, const Date& rhs)
{
return lhs.variable_ == rhs.variable_;
}
要将比较运算符实现为成员函数,只需要接受一个实参,即=
右边的值。拥有正在执行的比较运算符的对象是=
左侧的值。在这种情况下,操作符应该是const限定的。
struct Date
{
int variable_;
bool operator==(const Date& rhs) const
{
return variable_ == rhs.variable_;
}
};
在任何情况下,参数都应该作为const
引用,以允许使用右值(临时值)。
相关文章:
- QSqlquery prepare()和bindvalue()不工作
- 导入库可以跨dll版本工作吗
- 以螺旋方式打印矩阵的程序.(工作不好)
- 对象指针在c++中是如何工作的
- 为什么在Windows上的VS 2019和Clang 9中"size_t"在没有标题的情况下工作
- VSOMEIP-2个设备之间的通信(TCP/UDP)不工作
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- C++为线程工作动态地分割例程
- 为什么我的 std::ref 无法按预期工作?
- 布尔比较运算符是如何在C++中工作的
- SampleConsensusPrerejective(ext.RANSAC)是如何真正工作的
- 不确定要在我的main中放入什么才能使我的代码正常工作
- 为什么std::condition_variable notify_all的工作速度比notify_one快(对于随机请
- <<操作员在下面的行中工作
- 有人能解释一下为什么下界是这样工作的吗C++的
- ExtractIconEx:可以工作,但偶尔会崩溃
- C++中的memset函数工作不正常
- 为什么STD ::计数将常数传递给Lambda,而不是在弦上工作时而不是字符
- sdl软件渲染器不工作,工作在硬件加速的一个
- C++程序已停止工作-求解常微分方程