Can anyone tell me how I can pass an object to a C++ function?
Any better solution than mine?
#include<iostream>
using name开发者_如何学编程space 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;
}
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() const
and use:
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.
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
.
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.
精彩评论