如何正确使用模板类来处理C ++中的数组类?

时间:2015-01-18 03:11:43

标签: c++ arrays templates

我正在尝试编写模板类并使用它 管理一些数组。然后我在main.cpp中遇到了一些错误,没有任何关于如何修复的想法。 P / S:我的代码没有完成。还有一些构造函数和析构函数可供使用。我相信使用模板可以有效地处理具有各种数据类型的数组。但是,我是OOP和C ++的新手,所以我们非常感谢任何进一步的建议,评论和解释 感谢。

以下是我的错误:

main.cpp:9:22: error: ‘class array<int>’ has no member named ‘size’

main.cpp:10:9: error: no match for ‘operator[]’ in ‘a[m]’

main.cpp:11:6: error: ‘cout’ is not a member of ‘std’

main.cpp:11:21: error: name lookup of ‘m’ changed for ISO ‘for’ scoping [-fpermissive]

main.cpp:11:21: note: (if you use ‘-fpermissive’ G++ will accept your code)

main.cpp:11:22: error: no match for ‘operator[]’ in ‘a[m]’

Compilation failed.

file array.h:

#ifndef ARRAY_H
#define ARRAY_H

#include <string>           //for std::string
#include <vector>           //for std::vector

template <typename T> 
class array 
{
private: 
    size_t N1,N2,N3;
    std::vector<T> array1D; 
    std::vector<std::vector<T> > array2D; 
    std::vector<std::vector<std::vector<T> > > array3D;         
public:    
    // default constructor
    array();
    array(size_t); 
    array(size_t,size_t);
    array(size_t,size_t,size_t);

};
#endif

file array.cpp:

#include "array.h"

template <typename T> 
array<T>::array(size_t i)
{
    N1 = i;
    // make room for some elements
    array1D.reserve(N1);
}

template <typename T> 
array<T>::array(size_t i,size_t j)
{
    N1=i;
    N2=j;
    array2D.reserve(N1);
    for (int m=0; m < array2D.size(); m++)
        array2D[m].reserve(N2);        
}

文件main.cpp:

#include "array.h"
int main(int argc, char * argv[])
{
    size_t i=10;
    array<int> a(i);

    for (int m=0; m < a.size(); m++)
        a[m]=m;
        std::cout << a[m] ;
    return 0;
}

0 个答案:

没有答案