在类中初始化struct

时间:2011-05-19 06:41:13

标签: c++

这是允许的吗?

class object 
{
public:
    struct st_example {
        int i;
        int j;
        int 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
};

那样:

object testObj(1,2,3);

2 个答案:

答案 0 :(得分:0)

嵌套类型在C ++中无效,如下所示:

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

解决方案是嵌套类型中的std::vector<int>,并添加了max_allowed_size变量;

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

您可以使用max_allowed_size作为约束,这样就不会向向量添加的值多于允许包含的值。您可以致电c.size()以了解该向量当前包含的项目数。

答案 1 :(得分:0)

d中的st_example是什么?我没有看到任何变量d,所以 你不能初始化它,也不能在表达式中使用它。

如果您只是希望st_example包含一个大小的数组 在运行时确定,使用std::vector。试着这样做 你做不到工作;你定义一个本地st_example, 并且编译器必须知道要为它分配多少空间, 在编译时。

如果动态分配st_example的所有情况,那么 你可以玩一些肮脏的技巧:

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)
    {
    }
};

(形式上,这是未定义的行为;标准没有 保证operator new中设置的值仍然是 在构造函数中。然而,在实践中,它会起作用。)

客户端代码必须使用new (d) st_example(i, j)进行分配, 对c元素的访问权限为c()[i]。而在更多 一般情况下,您可能不得不担心对齐。 (这里,所有内容都是int,因此对齐工作正常 自动。)

但是我建议坚持使用std::vector。这是很多 更简单,更不易碎。