我们知道了如何使用变量作为函数的实参,类对象也可以作为实参传递给函数。
例如,以下函数具有一个接收 Rectangle 对象的形参:
void displayRectangle(Rectangle r)
{
cout << "Length = " << r.getLength() << endl;
cout << "Width = " << r.getWidth() << endl;
cout << "Area = " << r.getArea() << endl; '
}
以下代码创建了一个长度为 15 和宽度为 10 的 Rectangle 对象 box,然后将 box 对象作为参数传递给了 displayRectangle 函数:
Rectangle box(15, 10);
displayRectangle(box);
假设 Rectangle 类包含本示例中使用的成员函数 displayRectangle,则该函数将输出以下信息:
Length = 15
Width = 10
Area = 150
与常规变量一样,对象可以通过值或引用传递给函数。在 Rectangle 示例中,box 通过值传递给 displayRectangle 函数,这意味着 displayRectangle 函数会收到一个 box 的副本。如果 displayRectangle 调用任何 Rectangle 类设置器函数,那么它们将只会更改 box 的副本,而不是原来的 box。如果函数需要存储或更改对象成员变量中的数据,则必须通过引用将对象传递给它。
下面的程序说明了这一点:
#include
#include
#include
using namespace std;
class InventoryItem
{
private:
int partNum; // Part number
string description; // Item description
int onHand; // Units on hand
double price; // Unit price
public:
void storeInfo(int p, string d, int oH, double cost); // Prototype
int getPartNum()
{
return partNum;
}
string getDescription()
{
return description;
}
int getOnHand()
{
return onHand;
}
double getPrice()
{
return price;
}
};
void InventoryItem::storeInfo(int