c ++初始化字符串指针数组 [英] c++ initialization of an array of string pointers
问题描述
我想初始化一个 std :: string
指针的大小,我从一个构造函数中获取的数组。另外,我想对两个 int
数组执行相同的操作,但是下面的代码不能编译:
I want to initialize an array of std::string
pointers of size that i get from a constructor. Also, i want to do the same for two int
arrays but the code below doesn't compile:
class MyQuickInitArray
{
public:
MyQuickInitArray(int size)
{
if(size <= 0)
{
throw new std::exception;
}
_size = size;
_counter = 0;
A = new std::string[size];
B = new int[size];
C = new int[size];
}
std::string& operator[](int j) {
if(j > _size)
{
throw std::out_of_range("out of range");
}
if(((B[j]<0) || (B[j]>=_counter)) || (C[B[j]]!=j))
{
// A[j] points to junk
_counter++;
A[j] = new std::string;
B[j] = _counter-1;
C[_counter-1] = j;
return A[j];
}
// the cell was instantiated before
return A[j];
}
~MyQuickInitArray(){};
private:
std::string* A[];
int B[];
int C[];
int _size;
int _counter;
};
如何正确地声明一个我从ctor获取的数组?
How can i properly declare an array of size that i get from a ctor?
EDIT:
发生的错误是:
incompatible types in assignment of ‘std::string* {aka std::basic_string<char>*}’ to ‘std::string* [0]
而对于 int
数组:
incompatible types in assignment of ‘int*’ to ‘int [0]’
推荐答案
它们不是在C ++中声明静态数组的有效方式,数组大小需要在编译时知道。下面的代码不能在没有一些特殊扩展的标准C ++中编译。
They are not valid way of declaring static arrays in C++, array size needs to be known at compile time. Below code can't compile in standard C++ without some special extension.
std::string* A[];
int B[];
int C[];
如果你只是使用指针很好。 但是,最好考虑使用 std :: vector
If you are just playing with pointers that's fine. However, you'd better think of using std::vector
#include <vector>
std::vector<std::string> A;
std::vector<int> B;
std::vector<int> C;
我可以将您的代码重写为以下内容:
I may rewrite your code to below:
class MyQuickInitArray
{
public:
MyQuickInitArray(int size)
: A(size),
B(size),
C(size),
size_(size),
counter_(0)
{
}
std::string operator[](int j) const
{
return A.at(j);
}
private:
std::vector<std::string> A;
std::vector<int> B;
std::vector<int> C;
int size_;
int counter_;
};
这篇关于c ++初始化字符串指针数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!