2

我有一个通用数组类,logic_error如果它与非原始类型一起使用,它会抛出一个。

模板类:

#include <string>
#include <sstream>
#include <iostream>    

using namespace std;

#define NULL_ELEMENT        ((T)NULL)


template<class T> class Array
{    
public:    
    Array(const int size)
    {
        this->elements[size];
        this->size = size;
        ::fill_n(elements, size, NULL_ELEMENT); /* 1 */
    }


    // Output of the array
    string toString()
    {
        int i=0;
        stringstream ss;

        ss << "Array{ ";

        for( ; i<size-1; i++ )
        {
            ss << elements[i] << ", ";
        }

        ss << elements[i] << " }";

        return ss.str();
    }

    // ...

private:
    int size;
    T elements[];
};

测试代码:

工作(使用原始类型):

Array<int> arr(5);
cout << arr.toString() << endl;

数组填充0Array{ 0, 0, 0, 0, 0 }

失败(使用非原始类型):

Array<string> arr(size); // <-- Exception thrown here
cout << arr.toString() << endl;

抛出异常:

terminate called after throwing an instance of 'std::logic_error'
  what():  basic_string::_S_construct null not valid

这发生在Array课堂上,当::fill_()被称为 ( /* 1 */) 时。

我想用类型的 Null-Element 填充整个数组T(如果是 int 或NULLif 指针等,则为 0) - 而不遍历每个元素。memset()这不是一个好的解决方案,不是吗?

4

1 回答 1

4

这是你应该做的。这是具有正确类骨架的最少代码。

template<class T> 
class Array
{
     T  *m_elements;  //declare a pointer member 
     size_t m_size;   //count of the elements

public:    

    Array(size_t size) : m_size(size), m_element(new T[size]())
    {                // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
                     //    use member-initialization-list
    }

    ~Array(); //must define it

    Array(Array const & other); //must define it

    Array& operator=(Array const & other); //must define it

    Array(Array&& temporary); //better define it (in C++11)
    Array& operator=(Array&& temporary); //better define it (in C++11)

    //other
};

要了解为什么必须定义析构函数复制构造函数复制赋值更好地定义 移动构造函数移动赋值, 请参阅这些(按此顺序):

于 2013-01-05T22:14:16.837 回答