Reputation: 9643
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;
};
How can i properly declare an array of size that i get from a ctor?
EDIT:
The error that occurs is:
incompatible types in assignment of ‘std::string* {aka std::basic_string<char>*}’ to ‘std::string* [0]
And for the int
arrays:
incompatible types in assignment of ‘int*’ to ‘int [0]’
Upvotes: 0
Views: 2552
Reputation: 3571
I think you want to use std::vector<std::string>
or std::vector<int>
instead your array members. The whole code will be simpler.
But if you really want to use the arrays then you could try (Not that I recommended):
class MyQuickInitArray
{
public:
MyQuickInitArray(int size):_size(0),_counter(0),A(nullptr),B(nullptr),C(nullptr)
{
if(size <= 0)
{
throw new std::exception;
}
_size = size;
typedef std::string* pSTR;
A = new pSTR[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(){
for(int j=0; j<_size; ++j)
if(((B[j]<0) || (B[j]>=_counter)) || (C[B[j]]!=j))
delete A[j];
delete[]A; delete[]B; delete[]C;};
}
private:
std::string** A;
int *B;
int *C;
int _size;
int _counter;
};
Upvotes: 0
Reputation: 45410
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[];
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_;
};
Upvotes: 3