【问题标题】:Implementing Array Initializer实现数组初始化器
【发布时间】:2011-07-20 17:12:22
【问题描述】:

您可以在同一行声明和初始化常规数组,如下所示:

int PowersOfTwo[] = {1, 2, 4, 8, 16, 32, 64, 128};

有没有办法在自定义类中复制这种行为?所以,例如:

MyClass<int> PowersOfTwo = {1, 2, 4, 8, 16, 32, 64, 128};

你可以让一个拷贝构造函数接受一个数组作为它的参数,但是你仍然需要在上一行声明这个数组。

int InitializationArray[] = {1, 2, 4, 8, 16, 32, 64, 128};
MyClass<int> PowersOfTwo = InitializationArray; 

【问题讨论】:

    标签: c++ arrays oop syntax constructor


    【解决方案1】:

    你可以用这样的方式来实现你的类:

    MyClass<int> array;
    array = 1,2,3,4,5,6,7,8,9,10;//dont worry - all ints goes to the array!!!
    

    这是我的实现:

    template <class T>
    class MyClass
    {
       std::vector<T> items;
    public:
    
        MyClass & operator=(const T &item)
        {
           items.clear();
           items.push_back(item);
           return *this;
        }
        MyClass & operator,(const T &item)
        {
           items.push_back(item);
           return *this;
        }
        size_t Size() const { return items.size(); }
        T & operator[](size_t i) { return items[i]; }
        const T & operator[](size_t i) const { return items[i]; }
    
    };
    
    int main() {
    
            MyClass<int> array;
            array = 1,2,3,4,5,6,7,8,9,10;
            for (size_t i = 0 ; i < array.Size() ; i++ )
               std::cout << array[i] << std::endl;
            return 0;
    }
    

    输出:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    

    查看在线演示:http://www.ideone.com/CBPmj

    你可以在这里看到我昨天发布的两个类似的解决方案:

    Template array initialization with a list of values


    编辑:

    您可以使用类似的技巧来填充现有的 STL 容器。例如,你可以这样写:

    std::vector<int> v;
    v+=1,2,3,4,5,6,7,8,9,10,11,12,13,14,15; //push_back is called for each int!
    

    您只需将(), 运算符重载为:

    template<typename T>
    std::vector<T>& operator+=(std::vector<T> & v, const T & item)
    {
        v.push_back(item); return v;
    }
    template<typename T>
    std::vector<T>& operator,(std::vector<T> & v, const T & item) 
    {
        v.push_back(item); return v;
    }
    

    工作演示:http://ideone.com/0cIUD


    再次编辑:

    我是having fun with C++ operator。现在这样:

    std::vector<int> v;
    v << 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15; //inserts all to the vector!
    

    我觉得这个更好看!

    【讨论】:

    • 我想看看你试试。我认为你可能还需要一件事,因为逗号分隔的 int 列表也不知道它被分配的类型,并且赋值运算符的优先级最低,所以直到为时已晚才会发现(我认为)。跨度>
    • @Martin:我发布了工作代码的链接。也请看!
    • @Martin: operator,() 在所有二元运算符中的优先级最低,operator=() 首先被评估,然后是所有operator,()
    • @Xeo:没错……你解释得很好!
    • 几个线性代数库使用类似的技巧,特别是 Eigen:eigen.tuxfamily.org/dox-2.0/…
    【解决方案2】:

    只有当您的编译器支持initializer lists(C++0x 功能)时,才能做到这一点。

    否则,必须使用一些其他语法,如 boost.assign 库中的语法。

    【讨论】:

    • 爱上 Boost.Assign 页面开头的那句话,并立即展示了一个很好的例子:There appear to be few practical uses of operator,().
    猜你喜欢
    • 1970-01-01
    • 2021-06-03
    • 2018-01-15
    • 1970-01-01
    • 1970-01-01
    • 2020-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多