Initializing struct within a class
Is this allowable?
class object
{
public:
struct st_example {
int i;
int j;
i开发者_运维知识库nt c[d];
st_example(int i_i, J_j, d_d) : i(i_i), j(j_j), d(d_d) {}
};
object(int i_ii, int j_jj, int d_dd)
{
struct st_example test(i_ii, j_jj, d_dd);
}; // Constructor
};
So that:
object testObj(1,2,3);
What's d
in st_example
? I don't see any variable d
, so
you can't initialize it, nor use it in an expression.
If you simply want st_example
to contain an array whose size
is determined at runtime, use std::vector
. Trying to do it as
you do cannot be made to work; you define a local st_example
,
and the compiler has to know how much space to allocate for it,
at compile time.
If all cases of st_example
are allocated dynamically, there
are some dirty tricks you can play:
class st_example
{
public:
int i;
int j;
int size;
int* c() { return reinterpret_cast<int*>( this + 1 ); }
int const* c() const { return reinterpret_cast<int const*>( this + 1 ); }
void* operator new( size_t toAllocate, int n )
{
st_example* results =
static_cast<st_example*>(
::operator new( toAllocate + n * sizeof(int) ) );
results->size = n;
return results;
}
void operator delete( void* p )
{
::operator delete( p );
}
void operator delete( void* p, int );
{
::operator delete( p );
}
st_example(int i, int j)
: i(i)
, j(j)
{
}
};
(Formally, this is undefined behavior; The standard does not
guarantee that values set in the operator new
will still be
there in the constructor. In practice, however, it will work.)
Client code has to allocate using new (d) st_example(i, j)
,
and access to elements of c
is c()[i]
. And in the more
general case, you'll likely have to worry about alignment.
(Here, everything is int
, so the alignment works out
automatically.)
I'd recommend sticking with std::vector
, however. It's a lot
simpler, and a lot less fragile.
In nested type is not valid in C++ as indicated below:
struct st_example {
int i;
int j;
int c[d]; <------------------------------------------------- problem!
st_example(int i_i, J_j, d_d) : i(i_i), j(j_j), d(d_d)
};
The solution is std::vector<int>
in the nested type, with an addition of max_allowed_size
variable as;
struct st_example
{
int i;
int j;
int max_allowed_size; //maximum allowed size of the vector!
std::vector<int> c; //vector which contains the data
st_example(int i_i, J_j, d_d) : i(i_i), j(j_j), max_allowed_size(d_d)
};
You can use max_allowed_size
as constraint so that you don't add more values to the vector than its allowed to contain. You can call c.size()
to know how many items the vector is currently containing.
精彩评论