C++ 中的运算符重载 作为 int + 对象
我有以下课程:-
class myclass
{
size_t st;
myclass(size_t pst)
{
st=pst;
}
operator int()
{
return (int)st;
}
int operator+(int intojb)
{
return int(st) + intobj;
}
};
只要我像这样使用它,它就可以正常工作:-
char* src="This is test string";
int i= myclass(strlen(src)) + 100;
但我无法做到这一点:-
int i= 100+ myclass(strlen(src));
任何想法,我怎样才能实现这一点?
I have following class:-
class myclass
{
size_t st;
myclass(size_t pst)
{
st=pst;
}
operator int()
{
return (int)st;
}
int operator+(int intojb)
{
return int(st) + intobj;
}
};
this works fine as long as I use it like this:-
char* src="This is test string";
int i= myclass(strlen(src)) + 100;
but I am unable to do this:-
int i= 100+ myclass(strlen(src));
Any idea, how can I achieve this??
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在类外部实现运算符重载:
Implement the operator overloading outside of the class:
您必须将运算符实现为非成员函数,以允许左侧使用原始 int。
You have to implement the operator as a non-member function to allow a primitive int on the left hand side.
这里的其他答案将解决该问题,但以下是我在执行此操作时使用的模式:
这种方法的主要好处之一是您的函数可以相互实现,从而减少总体代码量你需要。
更新:
为了避免性能问题,我可能会将非成员运算符+定义为内联函数,如下所示:
成员操作也是内联的(因为它们在类主体中声明),所以所有代码应该非常接近添加两个原始
int
对象的成本。最后,正如 jalf 所指出的,一般需要考虑允许隐式转换的后果。 上面的示例假设从整型类型转换为“Num”是明智的。
The other answers here will solve the problem, but the following is the pattern I use when I'm doing this:
One of the key benefits of this approach is that your functions can be implemented in terms of each other reducing the amount of overall code you need.
UPDATE:
To keep performance concerns at bay, I would probably define the non member operator+ as an inline function something like:
The member operations are also inline (as they're declared in the class body) and so in all the code should be very close to the cost of adding two raw
int
objects.Finally, as pointed out by jalf, the consequences of allowing implicit conversions in general needs to be considered. The above example assumes that it's sensible to convert from an integral type to a 'Num'.
您需要一个全局函数 operator+( int, myclass ) 来执行此操作:
You need a global function operator+( int, myclass ) to do this: