运算符逗号重载
Operator comma overloading
我正在尝试了解有关运算符重载如何工作的更多信息。
我知道重载逗号运算符可能不是最好的主意,但这仅用于教学目的。
我希望以下代码使用我的重载运算符(我使用了括号,因为我知道逗号运算符的优先级最低)来构造包含 (1,2) 的向量,然后调用向量的赋值运算符。
但是,我收到一个错误:
no known conversion from argument 1 from 'int' to 'const std::vector<int>&'
我不明白为什么会这样。 (1,2)应该构造一个向量,所以它不应该试图从int
转换为vector<int>
?
#include <vector>
#include <utility>
using std::vector;
using std::move;
template <typename T>
vector<T> operator,(const T& v1, const T& v2)
{
vector<T> v;
v.push_back(v1);
v.push_back(v2);
return move(v);
}
int main()
{
vector<int> a;
a = (1,2);
return 0;
}
已经有一个应用于整数的逗号运算符的内置定义。您的模板甚至不在重载解析运行中,因为除非至少有一个参数是用户定义类型,否则无法重载运算符。
你可以做这样的事情:
template<typename T>
struct vector_maker
{
std::vector<T> vec;
vector_maker& operator,(T const& rhs) {
vec.push_back(rhs);
return *this;
}
std::vector<T> finalize() {
return std::move(vec);
}
};
int main() {
auto a = (vector_maker<int>(),1,2,3,4,5).finalize();
}
或者看看Boost.Assign,它允许这样的结构:
std::vector<int> a;
a += 1,2,3,4,5,6,7,8;
赋
值右侧的表达式被简单地计算为(1,2)
并退化为(2)
或2
,这是一个int
。
然后评估分配。左侧为vector<int>
型。您正在尝试将2
(int
)分配给a
(vector<int>
),并且由于没有从int
到vector<>
的转换,因此出现错误。
您将无法重载内置类型(如 int
)的运算符。
相关文章:
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 重载运算符new[]的行为取决于析构函数
- 为什么将值返回函数传递给重载=运算符对运算符函数有效,而对其他运算符无效
- 在 myVector 类中重载运算符 + 时出错
- 为什么常量词在重载运算符中不与 ostream 对象一起使用<<?
- 如何在 cpp 中重载运算符 +=?
- C++ 如何重载 [] 运算符并进行函数调用
- 重载运算符的范围是什么?它是否会影响作为类成员的集合的插入函数?
- 为什么我可以在不重载 "=" 运算符的情况下将一个对象分配给另一个对象?
- 重载运算符有地址吗?
- 如何迭代重载运算符 [] 的类?
- 重载运算符与添加问题
- 模板基类中的重载运算符
- 如何调用用于重载运算符"<<"的 friend 函数?
- 在 C++17 中的命名空间和子命名空间中重载运算符是不明确的
- 重载运算符<<采用谷歌 C++ 风格
- C++ 如何正确重载 + 运算符
- cout (<<) 重载运算符不打印减去的矩阵
- 如何在 c++ 中重载运算符 + 以便能够 whrite c_str = "smth" + c_str;
- 重载运算符*以获取对另一个类的实例的引用