0

我有一个与运算符重载有关的问题,定义一个类及其运算符重载函数很容易,如下代码所示:

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)失败!

4

3 回答 3

3

引用不能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-11T16:43:07.713 回答
3

您的误解始于要添加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-11T16:58:42.507 回答
1

当您用于=创建引用时,您根本没有调用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

当然,使用指针而不是引用会更容易。

于 2012-10-11T16:36:45.533 回答