传递结构或类对象

Passing structures or class objects

本文关键字:对象 结构      更新时间:2023-10-16
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