[英]Passing a class object as an argument in C++
假設我有一個名為foo的類,主要包含用於顯示數據的數據和類欄。 因此,如果我有foo的對象實例名為foobar,我將如何將其傳遞到bar :: display()? 像空欄::顯示(foobar和測試)?
是的,差不多。 或者,如果可能,使用const引用來表示該方法不會修改作為參數傳遞的對象。
class A;
class B
{
// ...
void some_method(const A& obj)
{
obj.do_something();
}
// ...
};
#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 ;
}
希望這可以幫助。
所以有兩種方式傳遞類對象(這是你要問的)作為函數參數i)將對象的副本傳遞給函數,這樣如果對象中的函數做了任何改變就不會反映在原始對象中
ii)將對象的基址作為參數傳遞給函數。在thsi方法中,如果調用函數對對象進行了任何更改,它們也將反映在orignal對象中。
例如,看看這個鏈接 ,它清楚地證明了傳遞值的使用和通過引用傳遞在Jim Brissom的答案中清楚地表明了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.