C++ 重载 + 运算符只有成员函数用于添加带有整数的类对象

标签 c++ operator-overloading member-functions

我想知道如何operator+ 成员函数和operator=成员将在 main 中写下以下声明.

我不想添加好友功能。

int main(){
  A obj1, obj2, obj3;

  obj2 = obj1 + 10;

  obj3 = 20 + obj1;

  return 0;

}

//Below is my class

//Please add necessary assignment and additions operator+ functions

class A{

   int i;

 public :

      A(){i = 0;}

     A& operator=(const A &obj){

        i = obj.i;
        return *this;
    }
};

最佳答案

你说你不想使用友元函数,但是强硬,这是正确的方法。您不需要自定义赋值运算符。隐式构造函数会自动将整数转换为 A 的实例。这将适用于您在 main 中的代码。

class A
{
public :
    A(int i = 0) : i(i) {}

    friend A operator + (const A& left, const A& right)
    {
        return A(left.i + right.i);
    }

private:
    int i;
};

关于C++ 重载 + 运算符只有成员函数用于添加带有整数的类对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25382172/

相关文章:

c++ - 重载 operator<< operator== 和 operator!=

c++ - 我想减少在 1 亿个复杂数据上用 C++ 计算 2D FFT 的时间

具有重载 = 运算符的 C++ 包装器

C++ volatile 成员函数

c++ - invoke_result with member (operator[]) 函数

c++ - 指向类的成员函数的指针

c++ - 摆脱 ShellExecute 造成的邪恶延迟

c++ - 16 bpp 到 32 bpp 的转换

C++:运算符,(逗号)似乎不起作用

python - 在 Python 中使用 '__rsub__' 方法的典型实例是什么?