RSS

Tag Archives: C/C++

C++: Passing by Reference

#include <iostream>
using namespace std;
class Ref{
	//p_data will be copied into _data1 by value
	//int _data1;

	int &_data2;
public:
	// This would reference _data to the parameter named p_data
	// not the variable i from main()
	//  Ref(int p_data):_data2(p_data){ 
	//  }

	// pass the reference of p_data to _data2
	// so now _data2 is an alias for i
	Ref(int &p_data):_data2(p_data){
	}

	ostream& print(ostream& os)const{
		return os<<_data2;
	}
};
ostream& operator<<(ostream& os,const Ref& C){
	return C.print(os);
}

int main(){
	char* s[] = {"Sdsd", "dfdf"};
	char as[] = "Sadsd";
	cout<<s[1]<<endl;
	cout<<as<<endl;
	int i = 10;
	Ref R(i);
	cout<<R<<endl;
	i = 234;
	cout<<R<<endl;
	return 0;
}
 
Leave a comment

Posted by on February 13, 2014 in Knowledge

 

Tags: