如何定义 STL(C++) 的运算符重载

How to define operator overloading for STL(C++).

本文关键字:运算符 重载 C++ STL 定义 何定义      更新时间:2023-10-16

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

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

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