C++ 指向类成员的指针

#include<iostream>
using namespace std;

#define CalculationAndPrint(ARG)  #ARG << ": " << ARG

class Demo {
public:
	int X{ 0 };
	int Y{ 0 };
public:
	Demo() {}
	Demo(int x, int y) :X(x), Y(y) {}
public:
	int getX() { return X; }
	int getY() { return Y; }
	friend ostream& operator<<(ostream& out, const Demo& demo) {
		return	out << "(" << demo.X << "," << demo.Y << ")";
	}
	void setPos(int x, int y) { X = x; Y = y; }
};

int main() {
	Demo demo;
	Demo *pdemo = &demo;
	int Demo::*pX = &Demo::X;
	int Demo::*pY = &Demo::Y;
	int (Demo::*pGetX)(void) = &Demo::getX;
	int (Demo::*pGetY)(void) = &Demo::getY;
	void (Demo::*setPos)(int, int) = &Demo::setPos;

	cout << CalculationAndPrint(demo.*pX) << endl;
	cout << CalculationAndPrint((demo.*pGetY)()) << endl;
	cout << CalculationAndPrint(demo) << endl;
	(demo.*setPos)(3, 4);
	cout << CalculationAndPrint((pdemo->*pGetX)()) << endl;
	cout << CalculationAndPrint(pdemo->*pY) << endl;

	system("pause");
	return 0;
}

结果:


猜你喜欢

转载自blog.csdn.net/baidu_41743921/article/details/80464080