gpt4 book ai didi

c++ - 你会禁止我设计和使用这个容器吗?

转载 作者:行者123 更新时间:2023-11-28 07:32:06 25 4
gpt4 key购买 nike

#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();
}

最佳答案

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

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

关于c++ - 你会禁止我设计和使用这个容器吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17449971/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com