C++【5】类与对象(三)

成员函数重载:类中的成员函数与前面介绍的普通函数一样,成员函数可以带有缺省的参数,也可以重载成员函数。重载时,函数的形参必须在类型或数目上不同。

缺省函数的成员函数

定义类的指针及如何用指针来引用对象

定义类的数组及数组中元素的引用

#include<iostream>
using namespace std;

class Ctest
{
	int x,y;
	int m,n;
public: 
	void setxy(int a,int b)
	{
		x = a;
		y = b;
	}
	void setxy(int a,int b,int c,int d)
	{
		x = a;y = b;m = c; n = d;
	}
	void dispxymn(int x)
	{
		cout<< x <<","<< y <<","<< m <<"," << n << endl<<endl;	 
	}
	void dispxymn()
	{
		cout<< x <<","<< y <<","<< m <<"," << n << endl<<endl;	 
	}
};

int main()
{
	Ctest obj1,obj2;

    //参数不同
	obj1.setxy(10,20);
	obj2.setxy(10,20,30,40);
    //参数 类型不同
    obj1.setxy(666);
    obj2.setxymn();
	
	return 0;	
}

 指针引用对象:

//指针引用对象
#include<iostream>
using namespace std;

class Ctest
{
	public :
		double sum()
		{
			return x+y;	
		}
		void setxy(double a,double b)
		{
			x = a;
			y = b;
		}	
		void dispxy()
		{
			cout <<"x="<<x<<","<<"y="<<y<<endl<<endl;
		}
	private:
		int x,y;
};



int main()
{
	Ctest obj1,obj2;  //定义对象
	Ctest *pobj;  //对象类的指针(对象指针)
	pobj = &obj1;
	
	pobj->setxy(3.4,6.6); //通过指针引用对象的成员函数
	pobj->dispxy();
	
	cout<<"x+y"<<pobj->sum()<<endl;
	return 0;	
}

this指针: 不同对象占据内存中的不同区域,他们所保存的数据各不相同,但对成员数据进行操作的成员函数的程序代码是一样的。

        当对一个对象调用成员函数时,编译程序先将对象的地址赋给this指针,然后调用成员函数,每次成员函数存取数据成员时,也隐含使用this指针。

#include<iostream>
using namespace std ;

class Ctest
{
	private:
		int x;
	public:
		int getx()const
		{
			return x;	
		}
		void setx(int x)
		{
			this->x = x;
			cout <<"this指针存储的内存地址为:"<<this<<endl<<endl;	
		}
	
};

int main()
{
	Ctest obj; //创建一个对象
	obj.setx(666);
	cout<<"对象obj在内存的地址为:"<< &obj <<endl;
	cout <<"对象obj所保存的值为:"<< obj.getx() << endl;
	cout <<endl;
	
 return 0;	
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值