能否创建一个包含对其他结构体的引用的结构体?如果可以,如何初始化这些引用?请参考下面的简短示例。
谢谢
typedef struct {
int a;
}typeInner1;
typedef struct {
int b;
}typeInner2;
typedef struct {
typeInner1 &one;
typeInner2 &two;
}typeOuter;
void fun2(typeOuter *p){
p->one.a =2;
p->two.b =3;
}
void fun(typeInner1 &arg1,typeInner2 &arg2){
typeOuter *ptr = new typeOuter;//<-- how to write initializer
fun2(ptr);
}
int main(){
typeInner1 arg1;
typeInner2 arg2;
fun(arg1,arg2);
//now arg1.a should be 2 and arg2.a=3
}
非常感谢您提供的所有意见。我还必须修改typeOuter的typedef才能使其正常工作。以下是完整的工作代码,供其他人查看此帖。
#include <cstdio>
typedef struct {
int a;
}typeInner1;
typedef struct {
int b;
}typeInner2;
typedef struct typeOuter_t {
typeInner1 &one;
typeInner2 &two;
typeOuter_t(typeInner1 &a1, typeInner2 &a2) : one(a1), two(a2) {}
}typeOuter;
void fun2(typeOuter *p){
p->one.a =2;
p->two.b =3;
}
void fun(typeInner1 &arg1,typeInner2 &arg2){
typeOuter *ptr = new typeOuter(arg1,arg2);
fun2(ptr);
}
int main(){
typeInner1 arg1;
typeInner2 arg2;
fun(arg1,arg2);
//now arg1.a shoule be 1 and arg2.a=3
fprintf(stderr,"arg1=%d arg2=%d\n",arg1.a,arg2.b);
}
typedef struct {...} foo;
不是“惯用语”,直接写struct foo {...};
更常见(并且可以让你直接使用foo
作为类型名称)。 - Mat