在 C++ 中将类对象作为参数传递 [英] Passing a class object as an argument in C++

查看:36
本文介绍了在 C++ 中将类对象作为参数传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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)?

推荐答案

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

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.

class A;

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

这篇关于在 C++ 中将类对象作为参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆