类和对象(2)

对象指针(this)

将所有类对象两两比较,得出体重最大的牛的信息。
#include<iostream>
using namespace std;

class Cow
{
private:
	char name[20];
	double weight;
public:
	Cow();
	Cow(char* nm,double weight);
	void ShowCow();
	Cow & tohev(Cow & c);
};

Cow::Cow()
{
	strcpy(name,"default");
	weight=380;
}

Cow::Cow(char *nm,double wt)
{
	strcpy(name,nm);
	weight=wt;
}

void Cow::ShowCow()
{
	cout << "this cow is" << name << ",its weight is" << weight << "." << endl; 
}

Cow & Cow::tohev(Cow & c)
{
	if(c.weight >weight)
		return c;
	else
		return *this;
}

int main()
{
	Cow farm[3]=
	{
		Cow("namo",350),
		Cow("mud",426),
		Cow("fleep",380),
	};
	int i;
	cout << "there are 3 cows below:" << endl;
	for(i=0;i<3;i++)
	{ 
		cout << "ForNo." << i+1 << "cow" << endl;
		farm[i].ShowCow();
	}
	Cow hev=farm[0];
	for(i=0;i<3;i++)
		hev=hev.tohev(farm[i]);
	cout << "the heaviest cow is:" << endl;
	hev.ShowCow();

	return 0;
}

这是结果

向函数传递对象

将对象,对象指针,对象引用作为函数参数传递的情况。
1,对象作物参数传
函数将为实参对象生成一个拷贝对象,函数体内这个拷贝对象的操作不会影响到实参对象。(对象作为i参数传递时,程序会调用拷贝构造函数, 如果类中使用了动态内存分配,就必须显示地提供一个拷贝构造函数,否则造成异常(同一内存空间析构两次))
2,对象指针作为函数参数
类似普通类型,将对象的地址(对象指针)传递给函数时,此时函数对象的操作将影响到对象本身。好处:对象复杂时,只是传递地址,效率高。
3,对象引用作为函数参数
由于引用的指针特性,形参对象引用只是实参对象的 别名,因此在函数中对形参对象操作会影响原来的对象。好处:使用对象引用比使用对象指针更直观,也更易理解。
例子:

#include<iostream>
using namespace std;

class Point
{
private:
	int x;
	int y;
public:
	Point(){x=0;y=0;}
	Point(int xa,int ya){x=xa;y=ya;}
	void Show()
	{
		cout << "Point(" << x << "," << y << ")" << endl;
	}
	void Add(int ix,int iy)
	{
		x=x+ix;
		y=y+iy;
	}
};

//值传递
void CallPoint1(Point pt)
{
	cout << "Passs by value:" << endl;
	pt.Add(2,2);
	cout << "For object pt:";
	pt.Show();
}

void CallPoint2(Point* pt)
{
	cout << "Pass by pointer:" << endl;
	pt->Add(2,2);
	cout << "For object pt:";
	pt->Show();
}

void CallPoint3(Point& pt)
{
	cout << "Pass by reference:" << endl;
	pt.Add(2,2);
	cout << "For object pt:";
	pt.Show();
}

int main()
{
	Point co1(2,2),co2(-1,3);
	Point* p=new Point;

	CallPoint1(co1);
	cout << "After calling,for object co1:";
	co1.Show();

	CallPoint2(p);
	cout << "After calling,for object *p:";
	p->Show();

	CallPoint1(co2);
	cout << "After calling,for object co2:";
	co2.Show();

	delete p;
	
	return 0;
}


函数不同,不用重载,按值和按引用传递若使用同一个函数名,调用产生二义性。只有在按值传递的情况下,原来的对象没有发生改变。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值