C++ 基础(七)C++类的定义和使用、一个类调用另一个类

主要参考:

http://c.biancheng.net/view/215.html

https://blog.csdn.net/rain722/article/details/55002321

一、C++类的定义和使用

#include "stdafx.h"
#include <iostream>
using namespace std;
class CRectangle
{
	public:
		void init(int w_, int h_); //成员函数,设置宽和高
		int area();                //成员函数, 求面积
		int perimeter();           //成员函数,求周长
	private:
		int w, h;                  //成员变量,宽和高
};                                 //必须有分号
void CRectangle::init(int w_, int h_)
{
	this -> w = w_;  this -> h = h_;
}
int CRectangle::area()
{
	return w * h;
}
int CRectangle::perimeter()
{
	return 2 * (w + h);
}

//class add
//{
//	public:
//		void addFunc(int wVar, int hVar);
//};
//
//void add::addFunc(int wVar, int hVar)
//{
//
//}

int main()
{
	int w, h;
	CRectangle  r;  //r是一个对象,相当于C#类的实例化
	cin >> w >> h;
	r.init(w, h);
	cout << "It's area is " << r.area() << endl;
	cout << "It's perimeter is " << r.perimeter();
	return 0;
}

二、一个类调用另一个类

在一个.cpp文件文件中,可以定义多个类,并且在该.CPP文件中,一个类可以访问另一个类。

参考:https://blog.csdn.net/qq_35721743/article/details/83592415

#include "stdafx.h"
#include<iostream>
#include<string>
using namespace std;

class Person
{
public:
	Person(int _age, string _name) :age(_age), name(_name) {}
	~Person() {};
	void print()
	{
		cout << name << "	" << age << endl;
	}
private:
	int age;
	string name;
};
class Teacher
{
public:
	Teacher(Person* _person) :person(_person) {}
	~Teacher() {};
	void print()
	{
		this->person->print();
	}
private:
	Person* person;

};

int main()
{
	Person p(40, "lisan");
	Teacher teacher(&p);
	teacher.print();
	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/xpj8888/article/details/85265737