本文介绍了如何将对象传递给 C++ 中的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 C++ 编程的新手,但我有 Java 的经验.我需要有关如何在 C++ 中将对象传递给函数的指导.

I am new to C++ programming, but I have experience in Java. I need guidance on how to pass objects to functions in C++.

我是否需要传递指针、引用或非指针和非引用值?我记得在 Java 中没有这样的问题,因为我们只传递保存对象引用的变量.

Do I need to pass pointers, references, or non-pointer and non-reference values? I remember in Java there are no such issues since we pass just the variable that holds reference to the objects.

如果您还可以解释在何处使用这些选项,那就太好了.

It would be great if you could also explain where to use each of those options.

推荐答案

C++11 的经验法则:

按值传递,除非

  1. 你不需要对象的所有权,一个简单的别名就可以了,在这种情况下,你通过const引用,莉>
  2. 你必须改变对象,在这种情况下,使用通过非const左值引用
  3. 您将派生类的对象作为基类传递,在这种情况下,您需要通过引用传递.(使用前面的规则来决定是否通过const 引用.)
  1. you do not need ownership of the object and a simple alias will do, in which case you pass by const reference,
  2. you must mutate the object, in which case, use pass by a non-const lvalue reference,
  3. you pass objects of derived classes as base classes, in which case you need to pass by reference. (Use the previous rules to determine whether to pass by const reference or not.)

实际上从不建议通过指针传递.可选参数最好表示为 std::optional(boost::optional 用于较旧的 std 库),并且通过引用可以很好地使用别名.

Passing by pointer is virtually never advised. Optional parameters are best expressed as a std::optional (boost::optional for older std libs), and aliasing is done fine by reference.

C++11 的移动语义使按值传递和返回即使对于复杂对象也更具吸引力.

C++11's move semantics make passing and returning by value much more attractive even for complex objects.

传递参数通过const引用,除非

  1. 它们将在函数内部进行更改,并且此类更改应反映在外部,在这种情况下,您通过非const 引用
  2. 该函数应该可以不带任何参数调用,在这种情况下,您可以通过指针传递,以便用户可以传递NULL/0/nullptr 代替;应用前面的规则来确定是否应该传递一个指向 const 参数的指针
  3. 它们是内置类型,可以复制传递
  4. 它们将在函数内部进行更改,并且此类更改不应反映在外部,在这种情况下,您可以通过复制strong>(另一种方法是根据之前的规则传递并在函数内部进行复制)
  1. they are to be changed inside the function and such changes should be reflected outside, in which case you pass by non-const reference
  2. the function should be callable without any argument, in which case you pass by pointer, so that users can pass NULL/0/nullptr instead; apply the previous rule to determine whether you should pass by a pointer to a const argument
  3. they are of built-in types, which can be passed by copy
  4. they are to be changed inside the function and such changes should not be reflected outside, in which case you can pass by copy (an alternative would be to pass according to the previous rules and make a copy inside of the function)

(这里,传值"被称为传值",因为传值总是在C++03中创建一个副本)

(here, "pass by value" is called "pass by copy", because passing by value always creates a copy in C++03)

还有更多内容,但是这几条初学者规则会让您走得更远.

There's more to this, but these few beginner's rules will get you quite far.

这篇关于如何将对象传递给 C++ 中的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-27 10:49
查看更多