链接时undefined reference to构造函数

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;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值