gpt4 book ai didi

c++ - 这是按引用传递还是按值传递?

转载 作者:太空宇宙 更新时间:2023-11-03 10:33:26 25 4
gpt4 key购买 nike

假设我有以下内容:

class MyClass
{
// ...
}

void doSomething (MyClass instance)
{
// Is instance passed by reference or by value (copied)?
}

void main ()
{
MyClass instance = MyClass();

doSomething(instance);
}

doSomething() 中的instance 是通过引用传递的吗?还是该类在内存中重复?还是别的?

最佳答案

这是按值传递

void doSomething (MyClass instance)

这是通过引用传递的

void doSomething (MyClass& instance)

这是通过常量引用传递的

void doSomething (const MyClass& instance)

此外,MyClass 不需要通过赋值构造。所以:

MyClass mc=MyClass();

实际上等同于:

MyClass mc; //no parens needed for default constructor (no args).

编辑:这是通过对 const 函数的 const 引用传递的,可以在 const 对象上调用 const 函数,因为它保证不修改对象状态。

void doSomething (const MyClass& instance) const

与许多不太严格的语言不同,Const 正确性被认为是 C++ 中的良好实践。

看我:

http://en.wikipedia.org/wiki/Const-correctness

http://www.gotw.ca/gotw/006.htm

关于c++ - 这是按引用传递还是按值传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9524640/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com