编程语言
首页 > 编程语言> > C++-面向对象(九)

C++-面向对象(九)

作者:互联网

友元
#include <iostream>
using namespace std;

class Point {
	// friend Point add(const Point &, const Point &);
	friend class Math;
private:
	int m_x;
	int m_y;
public:
	int getX() const { return this->m_x; };
	int getY() const { return this->m_y; };
	Point(int x, int y) :m_x(x), m_y(y) { }
};

class Math {
public:
	Point add(const Point &point1, const Point &point2) {
		return Point(point1.m_x + point2.m_x, point1.m_y + point2.m_y);
	}
};

//Point add(const Point &point1, const Point &point2) {
//	return Point(point1.m_x + point2.m_x, point1.m_y + point2.m_y);
//}

int main() {
	Point point1(10, 20);
	Point point2(20, 30);


	Point point = add(point1, point2);

	cout << endl;

	getchar();
	return 0;
}
内部类
#include <iostream>
using namespace std;

// Person
class Person {
private:
	static int ms_legs;
	static void other() {

	}
	int m_age;
	void walk() {

	}

	// Car
	class Car {
		int m_price;
	public:
		Car() {
			cout << "Car()" << endl;
		}

		void run() {
			Person person;
			person.m_age = 10;
			person.walk();

			ms_legs = 10;
			other();
		}
	};
public:
	Person() {
		cout << "Person()" << endl;

		Car car;
	}

	
};


int Person::ms_legs = 2;

class Point {
	class Math {
		void test();
	};
};

void Point::Math::test() {

}

int main() {
	cout << sizeof(Person) << endl;
	Person person;

	Person::Car car;

	getchar();
	return 0;
}
局部类
#include <iostream>
using namespace std;

int g_age = 20;

void test() {
	int age = 10;
	static int s_age = 30;

	// 局部类
	class Person {
	public:
		static void run() {
			g_age = 30;
			s_age = 40;

			cout << "run()" << endl;
		}
	};

	Person person;
	Person::run();
}

int main() {
	test();

	getchar();
	return 0;
}
类型转换

标签:const,point1,int,Point,C++,面向对象,point2,static
来源: https://blog.csdn.net/weixin_42528266/article/details/102756467