使用两个非类参数的 C++ 运算符重载(使用代理解决)
c++ operator overloading with two non-class arguments (solved with proxy)
我正在学习重载,我很好奇我是否可以用两个非类参数制作一个重载运算符。
例如,向量类具有要调用的 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 );
看起来不那么神奇,这通常是一件好事。
相关文章:
- 为什么比较运算符如此快速
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 使用C++中的模板和运算符重载执行矩阵运算
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 增量运算符与后缀混淆
- 一个关于在C++中重载布尔运算符的问题
- 运算符C++ "delete []"仅删除 2 个前值
- 模板类无法识别友元运算符
- 我可以使用条件运算符初始化C风格的字符串文字吗
- 关闭||运算符优化
- 通过继承类使用来自不同命名空间的运算符
- C++Cast运算符过载
- 如何使用AngelScript注册SFML Vector2运算符
- 重载元组索引运算符-C++
- 如何使用重载的相等(==)运算符向测试用例添加描述
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- 布尔比较运算符是如何在C++中工作的
- 重载运算符new[]的行为取决于析构函数
- 如何防止clang格式在流运算符调用之间添加换行符<<