运算符在C ++中重载为int + obj [英] Operator Overloading in C++ as int + obj

查看:86
本文介绍了运算符在C ++中重载为int + obj的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下类: -

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??

推荐答案

在类外部实现操作符重载:

Implement the operator overloading outside of the class:

class Num
{
public:
    Num(int i)
    {
    	this->i = i;
    }

    int i;
};

int operator+(int i, const Num& n)
{
    return i + n.i;
}

这篇关于运算符在C ++中重载为int + obj的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆