类外定义
文件内类外定义,类的定义和声明全部写在一个文件里面:
#include <iostream> #include <string> using namespace std; class teacher{ public: void setName(string _name); string getName(); void setGender(string _gender); string getGender(); void teach(); private: string strName; string strGender; }; void teacher::setName(string _name){ strName=_name; } string teacher::getName(){ return strName; } void teacher::setGender(string _gender){ strGender=_gender; } string teacher::getGender(){ return strGender; } void teacher::teach(){ cout << "上课" << endl; } int main() { teacher t; t.setName("A"); t.setGender("女"); cout << t.getName() + " " << t.getGender() << endl; t.teach(); return 0; }
文件外类外定义,将类分成两个文件定义,一个用来声明(.h文件),另一个用来写函数体(.cpp文件):
定义一个头文件:Teacher.h
#pragma once
#include <iostream>
#include <string>
using namespace std;
class Teacher {
public:
Teacher(string _name="aaa", string _gender="男"); // 构造函数
void setName(string _name);
string getName();
void setGender(string _gender);
string getGender();
void teach();
private:
string strName;
string strGender;
};
再把函数体写到一个cpp文件里面,Teacher.cpp:
#include <iostream>
#include <string>
#include <stdlib.h>
#include "Teacher.h"
#include "stdafx.h"
using namespace std;
Teacher::Teacher(string _name, string _gender):strName(_name),strGender(_gender) {
} // 初始化列表先于构造函数之前被加载,而且初始化列表可以对const变量赋值
void Teacher::setName(string _name) {
strName = _name;
}
string Teacher::getName() {
return strName;
}
void Teacher::setGender(string _gender) {
strGender = _gender;
}
string Teacher::getGender() {
return strGender;
}
void Teacher::teach() {
cout << "上课" << endl;
}
主程序:
// ConsoleApplication3.cpp: 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <stdlib.h>
#include <iostream>
#include <string>
#include "Teacher.h"
using namespace std;
int main()
{
Teacher t;
cout << t.getName() + " " << t.getGender();
t.teach();
Teacher t1("Tom","男");
cout << t1.getName() + " " << t1.getGender();
t1.teach();
system("pause");
return 0;
}