operator T()

#include
using namespace std;
class A {
public:
	int data;
	char datab;
	char* datac;
	A() { data = 0; datab = '4'; datac = &datab; }
	operator int& () { return data; }
	operator char& () { return datab; }
	operator char*& () { return datac; }
	

};


void main() {
	A a;
	int m = a;
	char b = a;
	char* c = a;

	(int)a + 1;
	cout << m << endl;
	cout << b << endl;
	cout << *c << endl;
    //0,4,4

	int &k = a;
	k++;
	cout << a << endl;
	cout << b << endl;
	cout << *c << endl;
    //1,4,4
    
    cout << (int)a << endl;
	cout << (char)a << endl;
    //1,4
    


}

在类中使用,可使类自动转换为某类型,一般用T&()就不用T(),否则会冲突。

你可能感兴趣的:(operator T())