指標運算子過載(* 和 ->)

嵌入式sw發表於2020-12-05
#include <iostream>
#include <stdlib.h> 
using namespace std;

class Arry{
public:
	Arry(const int len = 10):arr(new int[len]),size(len){
		for(int i = 0; i < size; i++){
			arr[i] = i;
		}
	}

	Arry(const Arry &obj):arr(new int[obj.size]),size(obj.size){
		for(int i = 0; i < size; i++){
			arr[i] = obj.arr[i];
		}
	}

	~Arry(){
		if(arr)
			delete [] arr;
	}

public:
	void setval(int post, int data){
		arr[post] = data;
	}
	int getval(int post){
		return arr[post];
	}

	int& at(const int id){
	 return arr[id];
	}
	
	int& operator[](const int id){
		return arr[id];
	}

private:
	int *arr;
	const int size;
};

class pointer{
public:
	pointer(Arry *p = NULL):ptr(p){
		if(NULL == ptr){
			::exit(-1);
		}
	}
	~pointer(){}
public:
	Arry *getaddr(){
		return ptr;
	}
	
	Arry& operator*(){
		return *ptr;
	}
	
	Arry* operator->(){
		return ptr;
	}
private:
	Arry *ptr;
	
};

int main()
{
	Arry a(20);
	cout << a.at(5) << endl;
	
	pointer p(&a);
	//p->就是a物件
	p->at(5) = 10; 
	(p.operator->())->at(5) = 25;
	(*p).at(5) = 56;
	cout << (*p)[5] << endl;
	
	pointer *q = new pointer(&a);
	(*q)->at(5) = 15; 
	
	return 0;
}

相關文章