C++ 在C+;中将类对象作为参数传递+;
假设我有一个名为foo的类,其中主要包含数据和用于显示数据的类栏。所以,如果我有一个名为foobar的foo对象实例,我将如何将它传递到bar::display()?类似于void bar::display(foobar&test)的东西?是的,差不多。或者,如果可能,使用const引用来表示该方法不会修改作为参数传递的对象C++ 在C+;中将类对象作为参数传递+;,c++,class,arguments,C++,Class,Arguments,假设我有一个名为foo的类,其中主要包含数据和用于显示数据的类栏。所以,如果我有一个名为foobar的foo对象实例,我将如何将它传递到bar::display()?类似于void bar::display(foobar&test)的东西?是的,差不多。或者,如果可能,使用const引用来表示该方法不会修改作为参数传递的对象 class A; class B { // ... void some_method(const A& obj) { ob
class A;
class B
{
// ...
void some_method(const A& obj)
{
obj.do_something();
}
// ...
};
#包括
福班
{
国际货币基金组织[2];
公众:
Foo(inta=10,intb=20);
void accessFooData()常量;
};
Foo::Foo(inta,intb)
{
m_a[0]=a;
m_a[1]=b;
}
void Foo::accessFooData()常量
{
std::cout所以有两种方法可以将类对象(这就是您所要求的)作为函数参数传递
i) 或者将对象的副本传递给函数,以这种方式,如果函数在对象中所做的任何更改都不会反映在原始对象中
ii)将对象的基址作为参数传递给函数。在thsi方法中,如果调用函数对对象进行了任何更改,它们也将反映在原始对象中
例如,看一看,它清楚地演示了传递值的用法,Jim Brissom的答案中清楚地演示了传递引用
#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 ;
}