模棱两可的重载:运算符(类对象,整数)

时间:2019-04-23 06:56:10

标签: operator-overloading c++17

我想学习模板和运算符重载的目的:比较向量/整数的长度。

例如(2,5)> 5 例如(1,0)<(5,2)

这是我的模板:

    template<class T, class U>
void vectorCmp(T x, U y)
{
    cout<<"Call Function Template"<<endl;

    // operator overloading
    if(x>y)
        cout<<x<<endl;
    else if(y>x)
        cout<<y<<endl;
    else if(x==y)
        cout<<"The length is equal"<<endl;
}

这是我的Vector类:

class Vector
{
    // operator overloading
    friend bool operator>(Vector & v1, Vector & v2);
    friend bool operator>(Vector & v, int l);
    friend bool operator>(int l, Vector & v);
    friend ostream & operator<<(ostream & os, Vector & v);
    friend ostream & operator<<(ostream & os, int l);

    private:
        int x;
        int y;

    public:
        Vector(int x, int y)
        {
            cout<<"Call Vector Constructor"<<endl;
            this->x = x;
            this->y = y;
        }

        ~Vector()
        {
            cout<<"Call Vector Destructor"<<endl;
        }
};

下面是朋友功能的定义:

    bool operator>(Vector & v1, Vector & v2)
{
    cout<<"Call operator overloading"<<endl;

    if(sqrt(pow(v1.x,2)+pow(v1.y,2))>sqrt(pow(v2.x,2)+pow(v2.y,2)))
        return true;
    else
        return false;
}

bool operator>(Vector & v, int l)
{
    cout<<"Call operator overloading"<<endl;

    if(sqrt(pow(v.x,2)+pow(v.y,2))>l)
        return true;
    else
        return false;
}

bool operator>(int l, Vector & v)
{
    cout<<"Call \'>\'operator overloading"<<endl;

    if(sqrt(pow(v.x,2)+pow(v.y,2))<l)
        return true;
    else
        return false;
}

ostream & operator<<(ostream & os, Vector & v)
{
    os<<"Call \'<<\' operator overloading"<<endl;

    os<<"The biggest length is "<<sqrt(pow(v.x,2)+pow(v.y,2))<<endl;

    return os;
}

ostream & operator<<(ostream & os, int l)
{
    os<<"Call \'<<\' operator overloading"<<endl;

    os<<"The biggest length is "<<l<<endl;

    return os;
}

比较向量/整数的长度时有以下三种情况:

->向量/整数

->向量/向量

->整数/向量

有两种情况可以退出:

-> cout <<向量

-> cout <<整数

下面是我的主要功能:

int main()
{
    int len = 10;
    Vector vec1(12,3);
    Vector vec2(2,5);

    vectorCmp(len,vec1);
    vectorCmp(vec2,len);
    vectorCmp(vec1,vec2);

    return 0;
}

编译时会发生错误!

错误:“ operator <<”的模棱两可的重载(操作数类型为“ std :: basic_ostream”和“ int”)

我不明白为什么用整数重载“ <<”是错误

感谢您解决我的问题!

1 个答案:

答案 0 :(得分:0)

出现错误的原因是因为您已声明:

A

operator of the same signature from the standard library不明确。