我只是试图制作一个比较 2 个对象的函数,但它给了我:
Error:
bool Duree::operator==(const Duree&, const Duree&)
must take exactly one argument
我该如何解决这个问题?谢谢。
杜里.h
#ifndef DEF_DUREE
#define DEF_DUREE
class Duree
{
public:
Duree(int heures = 0, int minutes = 0, int secondes = 0);
bool estEgal(Duree const& b) const;
bool operator==(Duree const& a, Duree const& b);
private:
int m_heures;
int m_minutes;
int m_secondes;
};
#endif
Duree.cpp
#include "Duree.h"
Duree::Duree(int heures, int minutes, int secondes) : m_heures(heures), m_minutes(minutes), m_secondes(secondes)
{
}
bool Duree::estEgal(Duree const& b) const
{
return (m_heures == b.m_heures && m_minutes == b.m_minutes && m_secondes == b.m_secondes);
}
bool operator==(Duree const& a, Duree const& b)
{
return a.estEgal(b);
}
main.cpp
#include <iostream>
#include "Duree.h"
using namespace std;
int main()
{
Duree fisrt(10, 10, 10), second(15, 20);
if (fisrt == second)
cout << "Les durees sont identiques";
else
cout << "Les durees sont differentes";
return 0;
}
最佳答案
要么将 operator==
声明为带有两个参数的自由函数:
bool operator==(Duree const& a, Duree const& b);
或者作为一个只有一个参数的成员函数:
bool Duree::operator==(Duree const& b);
这是因为当您执行 x == y
时,您只比较两个对象。如果您有一个成员函数,则会传递一个隐式的“this
对象”(您调用 operator==
的对象),使其成为 3 个参数而不是 2 个。
也就是说,从你编写代码的方式来看,我猜你只是忘了将 friend
放在 operator==
声明的前面,在类中定义。
可能有用的提示:您可以在支持它的编译器(基本上是每个“主要”编译器)上使用 #pragma once
,而不是包含守卫。 :)
关于C++ bool 运算符==,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23162870/