[英]C++ Overloading + operator with only member functions for addition of class object with integers
I want to know how the operator+
member function and operator=
member will be written for below statements in main
. 我想知道如何为
main
以下语句编写operator+
成员函数和operator=
成员。
I do not want to add friend functions. 我不想添加朋友功能。
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;
}
};
You say you don't want to use a friend function, but tough, that is the correct way. 您说您不想使用朋友功能,但是强悍,那是正确的方法。 You have no need for a custom assignment operator.
您不需要自定义分配运算符。 The implicit constructor will automatically turn the integer into an instance of A. This will work with your code in main.
隐式构造函数将自动将整数转换为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;
};
obj = obj1 + 10;
can be solved with the following defined operator: 可以使用以下定义的运算符解决:
A operator+( int rhs ){
return A( i + rhs );
}
the other way around is a problem, due to int being a non class type. 相反,由于int是非类类型,因此存在问题。 IMO you cannot solve this without friend operators, because member operators imply that the left hand system is a class type, you will need for overloading.
IMO,没有朋友运算符就无法解决此问题,因为成员运算符暗示左手系统是类类型,因此需要重载。
Here is a link to a very good answer to a similar question 这是指向类似问题的很好答案的链接
Slightly different solution: 略有不同的解决方案:
class A
{
public :
A(int i = 0) : i(i) {}
A operator+(int addition)
{
return A(i + addition);
}
private:
int i;
};
A operator+(int addition, const A& a)
{
return a + addition;
}
Operator= will work as you have written in your code snippet. Operator =将按照您在代码段中编写的那样工作。 For addition, member function will not work, one alternative is...
另外,成员函数将不起作用,一种替代方法是...
//Define following members functions and attributes in class
class A
{
private:
int i;
public:
//1) implicit constructor for conversion from int
A (int i_ = 0) : i (i_) {}
//2) public function for addition
A Add (A const& copy)
{ return A (i + copy.i); }
};
//You can call A::Add from global operator+ function without it being friend
A operator+ (A const& left, A const& right)
{ return left.Add (right); }
#include<iostream>
using namespace std;
class A{
int i;
public :
A(){i = 0;}
A& operator=(int obj){
i = obj;
return *this;
}
int operator+(){
return this->i;
}
int operator-(){
return -1*this->i;
}
A operator+(int a){
this->i=a+this->i;
return *this;
}
};
int main(){
A obj1, obj2, obj3;
obj2 = obj1 + 10;
obj3 = 20 + +obj1;
return 0;
}
Is that solve your problem?I hope this will help. 可以解决您的问题吗?希望对您有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.