我应该在传递结构时放置 & 吗?
Should I put & while passing a struct?
下面的代码正在传递结构变量:
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)
在测试中,您可以将代码更改为使用.
而不是->
相关文章:
- 我应该在C++中将这些结构用作参数化构造函数吗?
- 我应该如何在C++中使用结构体解决输入失败的问题?
- 我应该为地图使用哪种数据结构?(C++)
- 为什么我应该重载 () 运算符以在结构而不是类中priority_queue?
- 使用具有C++继承的 CMake 时,我应该如何组织我的目录结构?
- 在这种情况下,我应该为每个WSASend调用传递唯一的重叠结构吗?
- 我应该使用什么样的数据结构来实现UPGMA
- 我应该如何在恒定长度的 STL 样式数据结构中实现max_size?
- 我应该如何在 cpp 中设计结构?
- C++ - 创建游戏实体时,我应该使用"sub classes"还是结构?
- 我应该使用什么数据结构来对数据库/表进行建模
- 如何维护城市道路数据?(我应该使用什么数据结构)
- 我需要一个像堆栈一样的数据结构,但具有随机访问,但是,我应该实现什么
- 我应该如何共享数据结构
- 我应该在.h文件中还是在.cpp文件中放置POD结构
- 我应该使用(未记录的?)MINIDUMP_EXCEPTION_INFORMATION64结构来创建64位进程的转储吗
- 对于可以具有不同状态的结构,我应该使用哪种设计模式
- 我应该使用哪些键值数据结构?按值快速检索和按键快速检索
- 头文件中定义的多个结构 - 我是否应该将它们移出单独的 h 和 cpp 文件中
- C++ - 3-D 数据结构 - 我应该使用指针向量还是向量向量