在 C++ 中将类对象作为参数传递

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4551278/
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 15:43:33  来源:igfitidea点击:

Passing a class object as an argument in C++

c++classarguments

提问by Steve

Suppose I had a class named foo containing mostly data and class bar that's used to display the data. So if I have object instance of foo named foobar, how would I pass it into bar::display()? Something like void bar::display(foobar &test)?

假设我有一个名为 foo 的类,其中主要包含数据和用于显示数据的类 bar。因此,如果我有一个名为 foobar 的 foo 对象实例,我将如何将它传递给 bar::display()?类似于 void bar::display(foobar &test)?

回答by Jim Brissom

Yes, almost. Or, if possible, use a const reference to signal that the method is not going to modify the object passed as an argument.

是的,几乎。或者,如果可能,使用 const 引用来表示该方法不会修改作为参数传递的对象。

class A;

class B
{
    // ...
    void some_method(const A& obj)
    {
        obj.do_something();
    }
    // ...
};

回答by Mahesh

#include <iostream>

class Foo 
{
    int m_a[2];

    public:
    Foo(int a=10, int b=20) ;           
    void accessFooData() const;

};

Foo::Foo( int a, int b )
{
    m_a[0] = a;
    m_a[1] = b;
}

void Foo::accessFooData() const
{
    std::cout << "\n Foo Data:\t" << m_a[0] << "\t" << m_a[1] << std::endl;
}

class Bar 
{
    public:
    Bar( const Foo& obj );
};

Bar::Bar( const Foo& obj )
{
    obj.accessFooData();
   // i ) Since you are receiving a const reference, you can access only const member functions of obj. 
   // ii) Just having an obj instance, doesn't mean you have access to everything from here i.e., in this scope. It depends on the access specifiers. For example, m_a array cannot be accessed here since it is private.
}

int main( void )
{
    Foo objOne;
    Bar objTwo( objOne ) ;
    return 0 ;
}

Hope this helps.

希望这可以帮助。

回答by shailendra

so there are two way of passing class object(it is what you are asking) as a function argument i) Either pass the copy of object to the function, in this way if there is any change done by the function in the object will not be reflected in the original object

所以有两种方法可以将类对象(这是您要问的)作为函数参数传递 i)将对象的副本传递给函数,这样如果对象中的函数进行了任何更改,则不会反映在原始对象中

ii) Pass the base address of the object as a argument to the function.In thsi method if there are any changes done in the object by the calling function, they will be reflected in the orignal object too.

ii) 将对象的基地址作为参数传递给函数。在此方法中,如果调用函数对对象进行了任何更改,它们也会反映在原始对象中。

for example have a look at this link, it clearly demonstrate the usage of pass by value and pass by reference is clearly demonstrated in Jim Brissom answer.

例如看看这个链接,它清楚地展示了值传递和引用传递的用法在吉姆布里森的答案中清楚地展示了。