C++ bool 运算符==

标签 c++

我只是试图制作一个比较 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/

相关文章:

c++ - 为什么在c++中使用ios::sync_with_stdio(false)后printf先于cout执行?

c++ - 为 C++ 模板类提供 swap() 中断 std::swap()?

c++ - Hello World Qt 创建者

java - 如何在Android的Qt上使用HockeyApp SDK

c++ - 是否从函数未定义的行为返回取消引用的指针作为引用?

c++ - 将 googlemock 与非虚拟函数的假 impl 一起使用

c++ - G++ 提示 "undefined reference to"而 GCC 成功

c++ - 变量或字段 '...' 在 Arduino 编译器上声明为 void 错误

c++ - 在 Ubuntu 20.04 中为 RPI4 链接 WiringPi 共享对象库

C++ 多线程错误