简体   繁体   中英

C++ Class addition method

I have a C++ class that primarily contains an integer and I wish to ceate a method that adds two of them together, I dont want to overload the + operator.

I belive I have 2 options:

var_result = var1.add(var2);

var_result.add(var1, var2);

where var_result, var1 and var2 are of the same type.

I think the 1st one is more intuitive ot use, but the seccond one is not creating an instance which might give performance benefits. How should I go about making this decision? This is going to be directly visible to others using my code.

I realize I might be dicing with the "opinion based" closure of this question but hopefully there is some degree of objectivity here.

Write you add() method with the same (preferred) semantics used for operator+ : write a free method that returns a new object by value.

Example :

var_result = add(var1, var2);

var_result2 = add(var1, var2).add(var3, var4);

// etc...

It allows you to chain methods, and respect the usual semantics available for primitive types.

Note:

  • Usually, the free function operator+ would make use of the class member operator+= that you would define for your type, allowing also var_result += var1

So your final design should look like :

class X
{
  public:
    X& operator+=(const X& rhs) { ...; return *this; }
};

X add(X lhs, const X& rhs)
{
    return lhs += rhs;
}

Or if you don't want operator+= either (which would makes sense, at least for consistency) :

class X
{
  public:
    X& add(const X& rhs) { ...; return *this; }
};

X add(X lhs, const X& rhs)
{
    return lhs.add(rhs);
}

继续创建新项目,因为任何空间/时间性能成本都将很小,并且使用不可变对象具有明显的优势。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM