C++中的.h与.cpp文件

类文件是.h文件,main函数是.cpp文件

#include<iostream>
using namespace std;
class Square//.h文件 (头文件)
{
private:
	int n;
//private:
//	int m;//类里允许使用多个private,可以清晰的告诉自己是在后来加上去的,(方法同)
public:
	Square()//用构造函数给类的成员进行初始化,与类名相同,可以自动运行,无返回值类型,可以重载
	{
	 n=100;//做缺省值,直接初始化
	}
	Square(int nn = 100)//间接初始化
	{
		n = nn * nn;
	}
	void input();
	void output();
};
void Square::input()
{
	cout << "input n:"; cin >> n;
}
void Square::output()//放在类外面需要声明(当一个类中含有很多函数时,可以很清晰的看出一个类中的多个函数)
{
	cout << "square:" << n * n << endl;
}
int main()//是.cpp文件是可执行文件
{
	Square a1;
    a1.output();
	//a1.output();
	//Square* a2;
	//a2 = &a1;//注意a2一个地址(当有很多类,不同类之间含有同名函数,用指针类型比较方便)
	//a2->input();
	//a2->output();
	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_43312665/article/details/88200710