C++学习笔记(二十一)双目操作符[] 多目操作符()的重载 内部类型


学习重点:

双目操作符[]

 多目操作符()的重载 

内部类型


//设定一个数组
#include <iostream>
#include <cstring>
#include  <cstdlib>

using namespace std;
class A
{
private:
	int *p;
	uint n;
public:
	A(uint n):n(n)
	{
		p=new int[n];
		if(p == NULL ) throw 0;
		//memset(p,0,n*sizeof(int)); //
	}
	~A()
	{
		delete[ ] p;
	}
	
	uint size() const 
	{
		return n;
	}
	
	// 再次重申 
	//不能重载的有 ?: .号  ::号
	//必须用成员函数的有 = ,-> , [ ] , ( ) ,类型转换运算符

//[ ]是个双目运算符 
	int& operator[ ] (const uint& i) const
	{
		if(i >= n) throw 1;
		return p[i];
	}

//能不能再写个int& operator[ ](const char c) const 呢?
//这是不行的,因为调用x[1]时,这个1可以转化为int 也可以转化成char 有歧义

//char* 字符串
	int& operator[ ](const char* c) const
	{
		int i = atoi(c); //字符串转整数
		if(i < 0 || i >=n) throw 1;
		return p[i];
	}
	
	//原括号运算符 是个多目运算符
	void operator( ) (const int v)
	{
		for(uint i = 0; i<n ; i++)
		{
			p[i] = v;
		}
	}
	
	void operator( )(const char* s)
	{
		int v = atoi(s);
		cout << s <<  " " << v << endl;
		for(uint i = 0; i<n ; i++)
		{
			p[i]+=v;
		}
	}
	
	//对对象进行填充 begin 为初始值,delta为幅度
	int operator()(int begin,int delta)
	{
		for(uint i = 0; i< n ;i++)
		{
			p[i] = begin;
			begin += delta;
		}
		return p[n-1]; 
	}
	

};
class B
{
public:
	//在类内部空间可以定义类型成员。在外面要使用需要 B::Uint i; 才可以使用。私有干脆就不可见。
	typedef unsigned int Uint;
	struct Student
	{
		string name;
		int age;
	};
	
	enum Color{RED,WHITE,BLUE};
};

//只要不访问内部元素 就不一定要声明为友元。
ostream& operator<<(ostream& out,const A& a)
{
	out << '{';
	for(int i = 0; i< a.size();i++)
	{
		out << a[i] << " ";
	}
	out <<'}';
}


int main()
{
	A x(5), y(8);
	x[2] = 20; y[6] = 66;
	
	cout << x << endl;
	
	x["1"]= 123;
	cout << x <<endl;
	cout << x["1"] << endl;
	
	y(1); //将所有元素初始化为1
	cout << y << endl;
	y("2");//所有元素加2
	cout << y <<endl;
	
	A z(10); //创建对象
	cout << z(1,2) <<endl;  //从1开始以2递增 进行填充
	cout << z <<endl;
	
	
	//内部类型的使用
	
	B::Uint i =260;
	cout << i << endl;
	
	B:: Student abc = {"abc",20};
	B::Color c = B::WHITE;
	
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值