0
#include <iostream>
using namespace std;

//I want such a container that holds an array and don't want to expose array directly

template <size_t T>
class Container{
    public:
        Container(int in[]);
        int getValue(const unsigned int pos);
        //void setValue(const unsigned int pos,const int value);
        unsigned int getSize();
        /*...
        ...
        ...*/

        unsigned int theSize;
        int theArray[T];
};

template <size_t T>
Container<T>::Container(int in[]){
    theSize=T;
    for (unsigned int i=0;i<T;i++)
        theArray[i]=in[i];
}
template <size_t T>
int Container<T>::getValue(const unsigned int pos){return theArray[pos];}
template <size_t T>
unsigned int Container<T>::getSize(){
    return theSize;
}
//then I want to pass objects of this type around by address, but then to use that address //I have to do such design as follows, now would you prohibit me from doing this?

void someFunc(void * in){
    Container<1> * ptr=reinterpret_cast<Container<1> *>(in);
    unsigned int times=ptr->getSize();
    for (unsigned int i=0;i<times;i++)
        cout <<ptr->getValue(i)<<' ';
    cout <<'\n';

}

int main(int argc,char ** argv){

    int araye[10]={1,2,3,4,5,6,7,8,9,10};
    Container<10> obj(araye);

    someFunc(&obj);

    cin.get();
}
4

1 回答 1

1

是的,我会禁止你实现这个容器。您正在重新发明轮子,据我所知,没有理由这样做。

改用 a std::array。即使您不能使用 C++11(在哪里array引入),您也应该使用已经设计、构建和测试过的东西,例如std::vector.

于 2013-07-03T15:03:28.600 回答