寫了一個Course類,編譯g++ -std=c++11 Course.cpp時出現提示
剛看的C++ Primer,小白,還請給位前輩指點一下,謝謝。
Course.h
#ifndef COURSE
#define COURSE
#include <string>
#include <iostream>
using namespace std;
class Course{
friend istream &read(istream &,Course &);
friend ostream &print(ostream &,const Course &);
friend class CourseManager;
public:
explicit Course(string n="");
explicit Course(istream &is);
string getName() const;
void setName(const string &name);
private:
unsigned creatID();
unsigned course_id;
string course_name;
static unsigned ID; //靜態成員,目的是希望實例化一個對象時自動分配ID,在構造函數裡調用creatID()
};
unsigned Course::ID = 0;
istream &read(istream &,Course &);
ostream &print(ostream &,const Course &);
#endif
Course.cpp
#include "Course.h"
#include <string>
#include <iostream>
using namespace std;
//構造函數定義
Course::Course(string n):course_name(n),course_id(creatID()) { }
Course::Course(istream &is){
read(is,*this);
}
//接口部分成員函數
string Course::getName() const{
return course_name;
}
void Course::setName(const string &name){
course_name = name;
}
//封裝部分成員函數
unsigned Course::creatID(){
++ID;
return ID;
}
//定義類相關的非成員函數
istream &read(istream &is,Course &it){
is >> it.course_id >> it.course_name;
return is;
}
ostream &print(ostream &os,const Course &it){
os << it.course_id << " " << it.course_name;
return os;
}
編譯成可執行文件需要鏈接main函數的,所以需要定義main