0

我想做类似下面的代码片段:

using namespace std;

struct str {
    int *integs;
};

void allocator(str*& str1) {str1.integs=new int[2];}
void destructor(str*& str1) {delete [] str1.integs;}

int main () {

    str str1;
    allocator(str1);
    str1.integs[0]=4;
    destructor(str1);
    return 0;
}

但是,这不起作用;我收到错误:在“str1”中请求成员“integs”,它是非类类型“str ”*

这不可能与 struct 做,我需要一个类?我必须以某种方式使用 -> 运算符吗?想法?

4

2 回答 2

1

您将str1作为对指针的引用。你可能的意思是:

void allocator(str& str1) {str1.integs=new int[2];}
void destructor(str& str1) {delete [] str1.integs;}
于 2013-01-11T13:21:51.523 回答
1

str1 是对指针的引用,您应该使用

str1->integs

或将其用作参考:

void allocator(str& str1) {str1.integs=new int[2];}
void destructor(str& str1) {delete [] str1.integs;}

应该没问题

于 2013-01-11T13:23:16.417 回答