【发布时间】:2012-10-11 16:29:47
【问题描述】:
我有一个关于运算符重载的问题,定义一个类及其运算符重载函数很容易,如下代码所示:
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 gain_priority_array(const std::vector &weighting, const std::vector<int> &sample=NULL) 失败!
【问题讨论】:
-
你为什么不改变你的函数来接受指针,而不是引用?如果您只想传递
NULL作为默认参数。 -
顺便说一下,
operator=没有被默认参数调用。采用 int 的构造函数是:liveworkspace.org/code/84813303faa93e2b1359fa90c21adba8 -
引用旨在避免为 NULL。尝试将 NULL 作为引用传递似乎是一个糟糕的代码概念。
-
@chris 是的,那么我的问题是关于 STL 组件,如何为 STL 向量定义构造函数?
-
@feelfree,看看这个:en.cppreference.com/w/cpp/container/vector/vector。唯一可以采用
NULL的构造函数是显式的,因此您需要类似于const std::vector<int> &priority_array = std::vector<int>(NULL)的东西,它转换为一个空向量。如果它应该转换为无向量,则必须使用指针。