1

为什么以下代码中指示的行(在 main() 中)无法编译?

#include <iostream>
#include <string>
#include <map>

template< typename _T > struct Inventory : public std::map< _T, int >
{
    bool getat(int i, _T &t, int &n)
    {
        if ((i < 0) || (i >= (int)this->size())) return false;
        int c=0;
        typename std::map< _T, int >::iterator it = this->begin();

        while ((c < i) && (it != this->end())) { c++; it++; }
        t = (*it).first;
        n = (*it).second;
        return true;
    }
    Inventory &operator=(_T t) { (*this)[t]++; return *this; }
    Inventory &operator,(_T t) { return operator=(t); }
};

int main()
{
    int i=0, quantity;
    std::string item;

    //***Fails to compile:***
    //Inventory< std::string > inv = "a","b","c","a","c","d","e";  

    Inventory< std::string > inv;
    inv = "a","b","c","a","c","d","e";    //but this is fine
    inv = "e","f";

    while (i < (int)inv.size())
    {
        if (inv.getat(i, item, quantity)) 
                std::cout << i << ": " << item << " -> " << quantity << "\n";
        i++;
    }
    return 0;
}
4

2 回答 2

2

这称为复制初始化。简而言之,它使用转换构造函数,然后使用复制构造函数来构造inv,而不是operator =您期望的那样。

Inventory< std::string > inv = "a","b","c","a","c","d","e";  

是无效的语法。类似的东西Inventory< std::string > inv = "a"会首先尝试创建一个临时Inventoryfrom"a","b","c","a","c","d","e"然后使用该临时作为复制构造函数的参数来构造inv. operator =在这种情况下永远不会调用。

您的第二个版本有效,因为

Inventory< std::string > inv;

调用默认构造函数,并且

inv = "a","b","c","a","c","d","e"; 

调用operator =已经初始化的对象。

于 2012-10-10T10:49:35.583 回答
2

你的问题是,在一种情况下,逗号是标点符号(并且运算符重载不适用),而在另一种情况下,它是一个运算符。不起作用的定义基本上相当于:

Inventory<std::string> inv = "a";
Inventory<std::string> "b";
Inventory<std::string> "c";
//  ...

正因为如此,重载operator,总是不好的设计;当逗号是运算符时,当它不是时,太微妙了。

做这样的事情的通常方法是创建一个相关的类来收集参数,并将其传递给构造函数:

Inventory<std::string> inv = Collector().add("a").add("b")...;

您还可以重载运算符并使用它,而不是 function add。但是我看不到可能的运算符 ( <<,受ostream?) 启发,或者您可以重载构造函数和operator()of Collector,然后编写:

Inventory<std::string> inv = Collector("a")("b")...;

然后,您将使用相同的语法进行赋值。(您真的不想要适用于分配的东西,而不是适用于复制构造的东西。)

于 2012-10-10T11:28:09.107 回答