如何定义 STL(C++) 的运算符重载
How to define operator overloading for STL(C++).
我有一个与运算符重载有关的问题,很容易定义一个类及其运算符重载函数,如以下代码所示:
typedef std::vector<std::vector<int> > ARRAY;
class ABC
{
public:
ABC():a(0)
{
};
int a;
ABC& operator = (int value)
{
a = value;
return *this;
}
ABC(int value)
{
a = value;
}
};
void obtain_priority_array(const std::vector<double> &weighting, const ABC &priority_array=NULL)
{
}
int main()
{
vector<double> weighting;
weighting.push_back(0.8);
weighting.push_back(0.9);
weighting.push_back(0.6);
weighting.push_back(0.3);
weighting.push_back(0.5);
ABC test;
obtain_priority_array(weighting, test);
return 0;
}
在上面的示例中,class ABC
重新定义了operator =
,以便函数void obtain_priority_array(const std::vector<double> &weighting, const ABC &priority_array=NULL)
可以具有默认参数const ABC &priority_array=NULL
。我的问题是,如果函数中的最后一个参数来自 STL,例如 const std::vector<int> &priority_array=NULL
,我们如何重新定义operator =
。 谢谢!
编辑:void obtain_priority_array(const std::vector &weighting, const std::vector<int> &sample=NULL
) 失败!
您的误解始于添加operator=
以允许该类型的默认参数的建议。在您的示例中,它不是被调用operator=
,而是ABC(int)
。
使用 std::vector
时代码不被接受的原因是NULL
转换为 0(至少它几乎在所有你会看到它的时候都是这样),并且唯一可以采用 0 的 std::vector
构造函数,即计算多少项的构造函数,被标记为显式。
为了解决眼前的问题,可以将语法更改为:
const std::vector<int> &priority_array = std::vector<int>(0)
但是,这引入了不同的语义。通过使用NULL
,看起来你期望它不代表向量。如果未给出任何内容,此版本将提供一个空向量供使用。它根本不会是没有载体。如果你想要这种区别,你应该使用 boost 的可选库或一个简单的指针,因为引用不是正确的工具。
不能NULL
,你的问题与运算符重载无关。如果希望能够将NULL
作为默认值进行处理,请将参数类型从引用切换到指针。
void obtain_priority_array( const std::vector<double>& weighting,
const ABC *priority_array = NULL)
{
if( priority_array == NULL ) {
// blah
} else {
// more blah
}
}
另一种选择是使用 Boost.Optional 之类的东西来表示可选参数。
typedef boost::optional<ABC> maybe_ABC;
void obtain_priority_array( const std::vector<double>& weighting,
const maybe_ABC& priority_array = maybe_ABC() )
{
if( !priority_array ) {
// blah
} else {
// more blah
}
}
当您使用 =
创建引用时,您根本不会调用operator=
。您正在初始化引用。
您可以创建类的静态实例来表示 null 值,而不是使用 NULL
。
static const ABC ABC_NULL;
void obtain_priority_array(const std::vector<double> &weighting, const ABC &priority_array=ABC_NULL)
{
if (&priority_array == &ABC_NULL) // the default was used
当然,只使用指针而不是引用会更容易。
- 使用C++中的模板和运算符重载执行矩阵运算
- 为什么这个运算符<重载函数对 STL 算法不可见?
- <T> 通过模板化运算符重载将 std::complex 乘以双倍
- C++20概念:需要运算符重载
- 使用赋值运算符重载从类中返回jobject
- 在运算符重载定义中使用成员函数(const错误)
- 字节到位运算符重载C++
- 为什么在运算符重载时需要参考?
- 类中 c++ 的运算符 + 重载
- 算术复合运算符重载为非成员
- 运算符重载 (+),用于添加两个具有 C++ 的数组
- 交换运算符 + 重载会导致无限递归
- 如何理解新的运算符重载?
- 向量保持复数的运算符重载
- 如何创建运算符重载?
- 链接列表运算符重载没有打印出我想要的内容
- C++:需要帮助了解运算符重载错误
- 使用模板化运算符重载 XOR 运算符失败
- 如何确保接受的C++模板类型使运算符重载?
- 运算符重载使用运算符+添加类模板