我应该在传递结构时放置 & 吗?

Should I put & while passing a struct?

本文关键字:结构 我应该      更新时间:2023-10-16

下面的代码正在传递结构变量:

struct someStruct {
    unsigned int total;
};
int test(struct someStruct* state) {
    state->total = 4;
}
int main () {
    struct someStruct s;
    s.total = 5;
    test(&s);
    printf("ns.total = %dn", s.total);
}

(通过C中的引用传递结构中的源)

当用C++编程时,我可以在没有&的情况下通过这个结构吗?我是说

test(s); // or should test(&s);

如果我这样做,s会被复制吗?

在C++中,您可以使函数以引用为参数:

int test(someStruct& state) {
    state.total = 4;
}

你可以这样调用函数:

someStruct s;
test(s);

不会复制。在函数内部,state的行为与s类似。请注意,只有在C++中声明结构时才需要struct关键字。此外,在C++中,您的打印代码应该如下所示:

std::cout << "s.total = " << s.total << std::endl;

您必须包含iostream才能工作。

当您想更改传递给函数的结构的内容时,应该传递一个指针或通过引用传递,否则函数将修改正在创建的本地副本。

您可以传递指针

int test(struct someStruct* state);

通过参考

int test(struct someStruct &state);

在这两种情况下都不会创建副本&原结构将被修改
需要注意的是,通过引用传递是一种更为C++的方法。

test(&s);

pasess a pointer-to-s。你可以在你目前定义的接受指针的函数中使用这个:

int test(struct someStruct* state) 

如果您想通过引用传递,您可以将函数定义更改为

int test(struct someStruct& state) 

只需调用:

test(s)

在测试中,您可以将代码更改为使用.而不是->