unity让对象作为参数_C++类对象作为函数参数传递详解

我们知道了如何使用变量作为函数的实参,类对象也可以作为实参传递给函数。

例如,以下函数具有一个接收 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值