people.h文件中的People类构造函数没有函数体
#ifndef PEOPLE_H
#define PEOPLE_H
class People
{
public:
void setHeigth(double len);
double geHeigth(void);
People(); // 这是构造函数
private:
double length;
};
#endif
people.cpp文件中的实现了People类构造函数
#include <iostream>
#ifndef PEOPLE_H
#include "../include/people.h"
#endif
using namespace std;
// 头文件中的函数必须实现,不然会报 undefined reference to `People::People()'的错误
People::People(void)
{
cout << "Object is being created" << endl;
}
void People::setHeigth(double len)
{
length = len;
}
double People::geHeigth(void)
{
cout << "Object is being created" << endl;
return 1.8;
}
Cplus_cons_test.h文件中Line类中有一个数据成员People,必须包含people.h文件。
#ifndef CPLUS_CONS_TEST
#define CPLUS_CONS_TEST
#include "people.h"
typedef unsigned char FX_BYTE;
typedef const char *FX_LPCSTR;
class Line
{
public:
void setLength(double len);
double getLength(void);
Line(); // 这是构造函数
//People a();
private:
double length;
People people_p;
};
#endif
Cplus_cons_test.cpp文件中如果没有#include "people.cpp"这句而People类的构造函数没有函数体(也就是没有花括号‘{}’),链接时会报undefined reference to `People::People()'的错误。
#include <iostream>
#include "../include/Cplus_cons_test.h"
/**
* 这句包含非常重要,如果没有这句会报undefined reference to `People::People()'
*/
#include "people.cpp"
using namespace std;
// 头文件中的函数必须实现,不然会报 undefined reference to `Line::Line()'的错误
Line::Line(void)
{
cout << "Object is being created" << endl;
}
void Line::setLength(double len)
{
length = len;
// double l = People::geHeigth();
}
double Line::getLength(void)
{
return length;
}
main.cpp
#include <iostream>
#include "../include/Cplus_cons_test.h"
using namespace std;
// 程序的主函数
int main()
{
Line line;
// 设置长度
line.setLength(6.0);
cout << "Length of line : " << line.getLength() << endl;
system("pause");
return 0;
}