应该将哪些运算符声明为朋友? [英] What operators should be declared as friends?

查看:125
本文介绍了应该将哪些运算符声明为朋友?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一些书中以及经常在互联网上,我看到诸如"operator==应该被声明为朋友"之类的建议.

In some books and often around the internet I see recommendations like "operator== should be declared as friend".

我应该如何理解何时必须将运算符声明为好友,以及何时将其声明为成员?除了==<<之外,最经常需要将哪些运算符声明为好友?

How should I understand when an operator must be declared as friend and when it should be declared as member? What are the operators that will most often need to be declared as friends besides == and <<?

推荐答案

这实际上取决于类是位于对operator==(或其他运算符)的调用的左侧还是右侧.如果一个类将位于表达式的右侧,并且不提供对可以与左侧进行比较的类型的隐式转换,则需要将operator==作为单独的函数实现,或者作为该类的friend.如果操作员需要访问私有类数据,则必须 声明为friend.

This really depends on whether a class is going to be on the left- or right-hand side of the call to operator== (or other operator). If a class is going to be on the right-hand side of the expression—and does not provide an implicit conversion to a type that can be compared with the left-hand side—you need to implement operator== as a separate function or as a friend of the class. If the operator needs to access private class data, it must be declared as a friend.

例如,

class Message {
    std::string content;
public:
    Message(const std::string& str);
    bool operator==(const std::string& rhs) const;
};

允许您将消息与字符串进行比较

allows you to compare a message to a string

Message message("Test");
std::string msg("Test");
if (message == msg) {
    // do stuff...
}

但并非相反

    if (msg == message) { // this won't compile

您需要在课程内声明一个朋友operator==

You need to declare a friend operator== inside the class

class Message {
    std::string content;
public:
    Message(const std::string& str);
    bool operator==(const std::string& rhs) const;
    friend bool operator==(const std::string& lhs, const Message& rhs);
};

将隐式转换运算符声明为适当的类型

or declare an implicit conversion operator to the appropriate type

class Message {
    std::string content;
public:
    Message(const std::string& str);
    bool operator==(const std::string& rhs) const;
    operator std::string() const;
};

声明一个单独的函数,如果它不访问私有类数据,则无需成为朋友

or declare a separate function, which doesn't need to be a friend if it doesn't access private class data

bool operator==(const std::string& lhs, const Message& rhs);

这篇关于应该将哪些运算符声明为朋友?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆