這被稱爲執行和聲明的分離。將您的實現分開保存在cc
或cpp
文件中實際上是一個好主意。
因此,在您的標題:
//Person.h
#ifndef PERSON_H // <---- include header guards in your headers
#define PERSON_H
#include <string>
//using std::string; <--- you should remove this line, you don't want to import namespaces
// in your header file, or else they are imported in all
// files including this header
class Person{
public:
Person(const std::string &a, const std::string &b);
private:
std::string name, address; // qualify your names in the header
};
#endif
和您的實現文件:
//Person.cpp
#include "Person.h"
using namespace std; // <---- if you wish, import the std namespace in your global namespace
// in the implementation file
Person::Person(const string &a, const string &b):
name(a), // <---- correct syntax of initializer lists
address(b)
{
}