Cpp*_*Cpp 0 c++ comparison comparison-operators
我的程序中出现以下错误,用于将两个日期与 tda 日期进行比较。该操作必须返回短语“相同”或“不同”。
#include<iostream>
//#include<stdio.h>
#include<string.h>
using namespace std;
struct tfecha{
int dia;
int mes;
int anio;
};
int main()
{
tfecha f1,f2;
cout<<"Ingrese primera fecha:"<<endl;
cin>>f1.dia;
cin>>f1.mes;
cin>>f1.anio;
cout<<"Ingrese segunda fecha:"<<endl;
cin>>f2.dia;
cin>>f2.mes;
cin>>f2.anio;
if(strcmp(f1==f2){
cout<<"Las fechas son iguales:"<<endl;
}else
{
cout<<"Las fechas son diferentes:"<<endl;
}
}
Run Code Online (Sandbox Code Playgroud)
[错误] 与“operator ==”不匹配(操作数类型为“tfecha”和“tfecha”)
在最新版本的语言标准 C++20 中,该语言提供了可选的默认比较运算符。所以,就你而言:
struct tfecha {
int dia;
int mes;
int anio;
bool operator==(const tfecha&) const = default;
};
Run Code Online (Sandbox Code Playgroud)
意味着你可以比较tfecha。
要使用 C++20,您必须使用开关-std=c++20(对于 g++、clang++)或/std:c++20(对于 MSVC)等来调用 C++ 编译器。
看到它正在运行Godbolt。
其他注意事项:
请不要写using namespace std:
为什么是“using namespace std;” 被认为是不好的做法?
您不能使用strcmp()两个 tfecha 的比较结果。
您可以使用以下替代语法来默认比较运算符:
friend bool operator==(tfecha const&, tfecha const&) = default;
Run Code Online (Sandbox Code Playgroud)
这也有效,因为在较新的 C++ 版本中,您可以在类主体中定义友元函数。
我不想鼓励你用英语写作。但是,请注意,如果您的代码不仅要供您所在国家/地区的人们阅读 - 他们很可能会一些英语(因为 C++ 本身是用英语指定的,它的关键字也是如此),不太可能知道字段的意思是,并且不太可能意识到tefcha= t+fecha 并且 fecha 在卡斯特拉诺中意味着日期。