使用两个非类参数的 C++ 运算符重载(使用代理解决)

c++ operator overloading with two non-class arguments (solved with proxy)

本文关键字:运算符 C++ 代理 解决 重载 两个 参数      更新时间:2023-10-16

我正在学习重载,我很好奇我是否可以用两个非类参数制作一个重载运算符。

例如,向量类具有要调用的 x 和 y

vector += (4.5, -2.1);

谢谢!

编辑

我已经设法做到了这一点,并且还扩展为接受与用户创建的参数一样多的参数。这是它的样子:

//Point.hpp
class Point
{
friend class Proxy;
private:
double *val;
int i;
int amount;
public:
Point();
Point(const int&);
void Set(const int &);
double Get(const int &);
int Amount();
Proxy operator += (const double &add);
};
class Proxy
{
private:
int &i;
Point &temp_point;
public:
Proxy operator , (const double&);
Proxy(Point2D &, int&);
};

//Point.cpp
Point::Point()
{
    this->amount = 2;
    val = new double[this->amount];
    val[0] = 0;
    val[1] = 0;
};
Point::Point(const int &amount) : amount(amount)
{
    val = new double[amount];
    for (int i = 0; i < amount; i++)
    {
        val[i] = 0;
    }
};
void Point::Set(const int &nr)
{
    do
    {
        std::cout << "Give me value of " << nr << " coordinate: ";
        std::cin.clear();
        std::cin.sync();
        std::cin >> val[nr];
        if (std::cin.fail())
        {
            std::cout << "Try again, not acceptable...n";
        }
    } while (std::cin.fail());
}
double Point::Get(const int &nr)
{
    return val[nr];
}
int Point::Amount()
{
    return this->amount;
}
Proxy Point::operator += (const double &add)
{
    this->i = 0;
    this->val[i++] += add;
    return Proxy(*this, i);
}
Proxy::Proxy(Point &point, int &i) : temp_point(point), i(i)
{}
Proxy Proxy::operator , (const double &value)
{
    temp_point.val[i++] += value;
    return Proxy(temp_point, i);
}
//Source.cpp example
int main()
{
    Point example(3);
example += 4.5, -2.3, 3.0;
for (int i = 0; i < example.Amount(); i++)
    {
        std::cout << example.Get(i) << " ";
    }
    std::cout << std::endl;
    system("PAUSE");
    return 0;
}

希望有人觉得它有用。

这是行不通的,因为(4.5, -2.1)会调用内置的逗号运算符,并简单地计算-2.1。可以这样做:

vector += 4.5, -2.1;

这是有效的,因为,的优先级低于 += 。您可以重载+=以便它返回一个代理对象,而代理对象又具有将附加其他元素的重载,运算符。

您可以使用std::initializer_list

v & operator += (std::initializer_list<int> l)
{
    sum = std::accumulate(l.begin(), l.end(), sum);
    .....

您必须小心翼翼地将呼叫更改为

vector += {1 , 2};

如果你有一个对向量,一个更易读的选择是

vector += std::make_pair( 4.5, -2.1 );

看起来不那么神奇,这通常是一件好事。