【问题标题】:Implementing unary subtraction, negation, minus operator, "operator-" in class在类中实现一元减法、否定、减号运算符、“运算符-”
【发布时间】:2013-09-02 23:01:00
【问题描述】:

我正在研究实现一元“否定”、“符号反转”或“减法”运算符,可能作为我班级的友元函数。

我对正确方法的猜测是:

namespace LOTS_OF_MONNIES_OH_YEAH { // sorry, couldn’t resist using this namespace name

    class cents
    {

    public:
        cents(const int _init_cents)
            : m_cents(_init_cents)
        {
        }


    public:
        friend inline cents operator-(const cents& _cents);

    private:
        int m_cents;

    };


    inline cents operator-(const cents& _cents)
    {
        return cents(-(_cents.m_cents));
    }

}

我猜对了吗?

PS:理想情况下,命名空间名称应该小写,因为大写通常专门用于常量,但我认为大写提供了更大的影响。

PPS:摘自here的示例

【问题讨论】:

标签: c++ operator-overloading unary-operator


【解决方案1】:

一元运算符只接受一个参数(因此是一元)。如果你想将它实现为非成员函数,你可以这样定义它:

inline cents operator-(cents const& value)
{
    return cents(-value.m_cents);
}

当然friend声明的签名需要和定义匹配。

【讨论】:

  • @EdwardBird:那你有什么问题...?
  • 要求确认我的猜测是否正确。我怀疑我错过了什么,但看起来我第一次(第二次)做对了?如果不确定,通常也可以提出问题。就搜索结果而言,之前没有人问过问题。
  • @EdwardBird:好的,很公平。顺便说一句,只是为了好玩:您还可以定义一元加:inline cents operator+(cents value) { return value; } 它很少特别有用,但为了完整性......
  • 是的好主意 - 似乎是实现两者的好主意。我假设没有operator+,如果我尝试执行以下操作,编译器会抱怨:cents c1(10); cents c2(12); c1 = +c2 ?
  • @EdwardBird:是的,这是正确的。但是,很少使用这样的表达方式。
猜你喜欢
  • 1970-01-01
  • 2016-08-24
  • 2021-12-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-03
相关资源
最近更新 更多