c++ - 如何将对象传递给函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7626116/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 17:14:37  来源:igfitidea点击:

How to pass object to function in c++?

c++

提问by baljeet Singh

Can anyone tell me how I can pass an object to a C++ function?

谁能告诉我如何将对象传递给 C++ 函数?

Any better solution than mine?

有比我更好的解决方案吗?

#include<iostream>
using namespace std;
class abc
{
      int a;
      public:
             void input(int a1)
             {
                  a=a1;
             }
             int display()
             {
                  return(a);
             }   
};

void show(abc S)
{
    cout<<S.display();
}

int main()
{
    abc a;
    a.input(10);
    show(a);
    system("pause");
    return 0;
}

回答by Flexo

You can pass by value, by reference or by pointer. Your example is passing by value.

您可以按值、按引用或按指针传递。您的示例是按值传递。

Reference

参考

void show(abc& S)
{
    cout<<S.display();
}

Or, better yet since you don't modify it make it int display() constand use:

或者,更好,因为您不修改它int display() const并使用:

void show(const abc& S)
{
    cout<<S.display();
}

This is normally my "default" choice for passing objects, since it avoids a copy and can't be NULL.

这通常是我传递对象的“默认”选择,因为它避免了副本并且不能为 NULL。

Pointer

指针

void show(abc *S)
{
    cout<<S->display();
}

Call using:

调用使用:

show(&a);

Normally I'd only use pointer over reference if I deliberately wanted to allow the pointer to be NULL.

通常,如果我故意允许指针为NULL.

Value

价值

Your original example passes by value. Here you effectively make a local copy of the object you are passing. For large objects that can be slow and it also has the side effect that any changes you make will be made on the copy of the object and not the original. I'd normally only use pass by value where I'm specifically looking to make a local copy.

您的原始示例按值传递。在这里,您可以有效地制作您正在传递的对象的本地副本。对于可能很慢的大型对象,它还具有副作用,即您所做的任何更改都将在对象的副本上而不是原始对象上进行。我通常只在我特别希望制作本地副本的地方使用按值传递。