我有一个与操作符重载有关的问题,很容易定义一个类及其操作符重载函数,如下代码所示:
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::Vector&W加权, 失败!)
发布于 2012-10-11 16:58:42
您的误解从添加operator=以允许该类型的默认参数的建议开始。在您的示例中,调用的不是operator=,而是ABC(int)。
在使用std::vector时,您的代码没有被接受的原因是,NULL转换为0(至少在您将看到它的所有时间内都是如此),而std::vector的唯一构造函数可以取0,即对多少项进行计数的构造函数是显式的。
要解决眼前的问题,可以将语法更改为:
const std::vector<int> &priority_array = std::vector<int>(0)然而,这引入了不同的语义。通过使用NULL,看起来您希望它不会表示任何向量。这个版本将提供一个空向量供使用,如果没有给出。它根本就不是一个载体。如果需要这种区别,则应该使用boost的可选库或简单指针,因为引用不是正确的工具。
发布于 2012-10-11 16:43:07
引用不能是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
}
}发布于 2012-10-11 16:36:45
当您使用=创建引用时,根本没有调用operator=。你在初始化引用。
您可以创建类的静态实例来表示空值,而不是使用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当然,只使用指针而不是引用就更容易了。
https://stackoverflow.com/questions/12844291
复制相似问题