传递结构或类对象
Passing structures or class objects
struct anup1 {
int a;
};
void structpass_1(struct anup1 b) // accepting structure
{
cout << b.a;
};
void structpass_2(struct anup1& b) // accepting address of a structure
{
cout << b.a;
};
int main() {
struct anup1 a2;
a2.a = 100;
structpass_1(a2);
structpass_2(a2);
}
上面的代码给出了相同的输出...接受参数是否为结构/结构的地址。
谁能向我解释一下这种行为?
谢谢
它将对结构 anup1 的引用传递给函数。
void structpass_2( struct anup1 &b)
看看什么是参考:参考
此外,函数参数列表中不需要关键字struct
,可以这样写:
void structpass_1(anup1 b) // accepting structure
void structpass_2(const anup1& b) // accepting address of a structure
如果参数是只读的,则const
参数添加
structpass_1
您的结构anup1
是按值传递的,因此完成本地副本并将其传递给函数。
相反,在structpass_2
中,结构被传递by reference
,即指向结构实例的指针被传递给函数(你有指针语义但值语法(。不会完成整个结构的本地副本。
请注意,对于仅包含一个整数的简单结构,从性能角度来看,按值或按引用传递是相同的。但是,当您拥有更复杂(和更大(的数据时,通过引用传递效率更高。
按值传递与按引用传递这两种情况之间的重要区别是,如果修改函数体内的结构实例,则仅当通过引用传递结构时,修改才会在调用站点持久存在。相反,当您按值传递结构时,由于本地复制是在函数体内完成的,因此当函数退出时,修改将丢失。例如:
void structpass_1(anup1 b) // pass by value
{
cout << b.a << 'n';
b.a++; // modification lost at the call site
};
void structpass_2(anup1& b) // pass by reference
{
cout << b.a << 'n';
b.a++; // the caller will see the incremented value for b.a
};
int main()
{
anup1 a2;
a2.a = 100;
structpass_1(a2); // will print 100
structpass_2(a2); // will print 100
cout << a2.a; // willl print 101 (structure modified by structpass_2)
}
void structpass_2( struct anup1 &b)
这是参考。 指针将带有*
。
第二个函数
void structpass_2( struct anup1 &b)
在C++语法是通过引用传递的,通过引用传递将简单地将对象的地址传递到函数中。
虽然第一个函数
void structpass_1(struct anup1 b)
使用按值传递。它将首先创建结构 a 的副本,然后传递给函数。按引用传递效率更高。
这些函数对于程序员来说是等价的,它们唯一的区别是在底层机器代码中 - 第一个对副本(对象(进行操作,第二个通过引用对原始对象进行操作(所以实际上是一个指针(。
您获得的输出是 100% 正确的。
简单地说,第一个创建对象的精确副本。这对于优化代码很有用,但请记住,如果您不想修改原始对象,请使用 const。
- 在nlohmann json中,如何将嵌套对象的数组转换为嵌套结构的向量
- 具有引用成员的结构是否具有唯一的对象表示形式
- 为什么我们再次从结构对象创建结构变量?
- 在什么情况下,两个堆栈分配的结构对象的 this 点指向同一个地址?
- C++:对象将 lambda 存储到结构中,稍后调用该函数
- 如何在C++中表示JSON文档的递归对象结构?
- 哪些值存储在对齐的结构/类对象的填充字节中
- 结构对象的指针成员在传递给函数时被修改
- C++ 提升 - 包含类层次结构对象的类的序列化
- 在 c++ 中使用字符串变量选择静态类结构,而不带对象
- 如何通过不同的指针使用类的对象访问结构?(链表)(C++)
- 是否可以在C++ (C) 中使用全局范围对象(结构)?
- 将数组/对象/结构列表从C#库中传递给C MFC应用程序
- 如何使用方法返回指向对象结构的指针?
- 对象/结构等的C++内存布局是什么?
- 这些不同的对象结构之间有什么区别
- 如何找到C++可执行文件的所有对象(类对象/结构)
- C/C++ 中的对象/结构对齐
- 额外的继承对对象结构或实例化有影响吗?
- 尝试处理嵌套对象/结构和动态数组时出现内存泄漏或内存错误。可能的 Xcode/malloc 问题