在 C++ 中使用 class 作为操作数的操作成为可能
Making operations with a class as an operand possible in C++
我对运算符重载相当熟悉,但是我想知道我们如何实现这样的东西:
myClass myclassobj;
int x;
x = 5;
x = x + myclassobj
无法为 int class 重载 + 运算符,因此应该从 myClass 做一些事情,但我们该怎么做呢?我可能使用了错误的关键字,但通过 SO 搜索并没有导致任何结果。抱歉,如果我做错了什么,这是我第一次 post 在这里。
编辑 - 我的 class 是一个自定义矢量 class,所以简单地将它转换为给定类型是行不通的。
使用签名 int operator+(int, myClass)
.
定义重载运算符
你是对的。
There is no way to overload the + operator for the int class, so
something should be done from myClass
您的问题:
but how would we do that?
我的回答:
You should use user defined type conversion. It may work with a conversion operator.
#include <iostream>
class myClass
{
int i;
public:
myClass(int i=0) : i(i) { }
operator int(){ // A conversion from myClass to int may solve your problem.
return i;
}
};
int main()
{
myClass myclassobj(99);
int x=7;
x = 5;
x = x + myclassobj;
std::cout<<x<<std::endl;
return 0;
}
Brian 也给出了一个很好的答案,但只有当重载运算符不需要来自第二个参数的受保护或私有成员或者如果重载运算符被声明为 myClass 的友元时,它才有效。
我对运算符重载相当熟悉,但是我想知道我们如何实现这样的东西:
myClass myclassobj;
int x;
x = 5;
x = x + myclassobj
无法为 int class 重载 + 运算符,因此应该从 myClass 做一些事情,但我们该怎么做呢?我可能使用了错误的关键字,但通过 SO 搜索并没有导致任何结果。抱歉,如果我做错了什么,这是我第一次 post 在这里。
编辑 - 我的 class 是一个自定义矢量 class,所以简单地将它转换为给定类型是行不通的。
使用签名 int operator+(int, myClass)
.
你是对的。
There is no way to overload the + operator for the int class, so something should be done from myClass
您的问题:
but how would we do that?
我的回答:
You should use user defined type conversion. It may work with a conversion operator.
#include <iostream>
class myClass
{
int i;
public:
myClass(int i=0) : i(i) { }
operator int(){ // A conversion from myClass to int may solve your problem.
return i;
}
};
int main()
{
myClass myclassobj(99);
int x=7;
x = 5;
x = x + myclassobj;
std::cout<<x<<std::endl;
return 0;
}
Brian 也给出了一个很好的答案,但只有当重载运算符不需要来自第二个参数的受保护或私有成员或者如果重载运算符被声明为 myClass 的友元时,它才有效。