本文介绍了在类内部或外部重载操作符有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++中我知道有两种方式来重载我们可以重载它内部(类a)或外部(类b)。但问题是在编译时或运行时这两者之间是否有任何差异?

  class a 
{
public:
int x;
a operator +(a p)//操作符在类$ b中重载$ b {
a temp;
temp.x = x;
temp.x = p.x;
return temp;
}
};

class b
{
public:
friend b operator +(b,b);
int x;
};

b operator +(b p1,b p2)//操作符在类外重载
{
p1.x + = p2.x;
return p1;
}


解决方案

c> operator + 要求LHS为 a - 自由运算符要求LHS RHS为 b ,另一侧可转换为 b

  struct Foo {
Foo(){}
Foo(int){}
Foo operator +(Foo const& R){return Foo }
};


struct Bar {
Bar(){}
Bar(int){}
};

bar操作符+(Bar const& L,Bar const& R){
return Bar();
}


int main(){
Foo f;
f + 1; //将工作 - int转换为Foo
1 + f; //不工作 - 没有匹配的运算符
Bar b;
b + 1; //将工作 - int转换为Bar
1 + b; // will work,int convert to a Bar for use in operator +

}


in C++ i know there are two ways to overload we can overload it inside (like class a) or outside (like class b). but the question is is there any diffrence between these two either in compile time or runtime or not?

class a
{
public:
    int x;
    a operator +(a p) // operator is overloaded inside class
    {
        a temp;
        temp.x = x;
        temp.x = p.x;
        return temp;
    }
};

class b
{
public:
    friend b operator +(b,b);
    int x;
};

b operator+(b p1,b p2) // operator is overloaded outside class
{
    p1.x +=p2.x;
    return p1;
}
解决方案

The member operator+ requires the LHS to be an a - The free operator requires LHS or RHS to be a b and the other side to be convertible to b

struct Foo {
    Foo() {}
    Foo(int) {}
    Foo operator+(Foo const & R) { return Foo(); }
};


struct Bar {
    Bar() {}
    Bar(int) {}
};

Bar operator+(Bar const & L, Bar const & R) {
    return Bar();
}


int main() {
    Foo f;
    f+1;  // Will work - the int converts to Foo
    1+f;  // Won't work - no matching operator
    Bar b;
    b+1;  // Will work - the int converts to Bar
    1+b;  // Will work, the int converts to a Bar for use in operator+

}

这篇关于在类内部或外部重载操作符有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 09:45