我的类继承代码遇到了麻烦:编译器无法识别构造函数。任何成员函数都不是。 例如,如果我调用构造函数, 我的测试文件(test.cpp)是这样开始的:
#include "salariedemployee.h"//This is a class inherited from 'employee.h', the base class
#include "Administrator.h"//This is a class inherited from "salariedemployee.h"
#include <iostream>
#include <string>
using std::cout;
using std::endl;
using namespace employeessavitch;
int main()
{
Employee boss("Mr Big Shot","987-65-4321");//I try to call constructor in the base class "employee";
}
编译器报错
undefined reference to `employeessavitch::Employee::Employee(std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::basic_string<char, std::char_traits<char>, std::allocator<char> >)'
如果我尝试调用继承类中的构造函数,例如
SalariedEmployee boss("Mr Big Shot","987-65-4321",10500.50);//a constructor about name, SSN number, and salary
它给出如下错误:
undefined reference to `employeessavitch::SalariedEmployee::SalariedEmployee(std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::basic_string<char, std::char_traits<char>, std::allocator<char> >, double)'
我想知道这是怎么回事?
我的基类头文件写成:
#ifndef EMPLOYEE_H
#define EMPLOYEE_H
#include <string>
using namespace std;
namespace employeessavitch
{
Employee( );//default constructor
Employee(string the_name, string the_ssn); constructor about name and ssn
}#endif
我继承的类头文件是这样写的:
#ifndef SALARIEDEMPLOYEE_H
#define SALARIEDEMPLOYEE_H
#include <string>
#include "employee.h"
using namespace std;
namespace employeessavitch
{
class SalariedEmployee : public Employee
{
public:
SalariedEmployee( );//default constructor
SalariedEmployee (string the_name, string the_ssn, double the_weekly_salary);//constructor about name, ssn and salary
//Other member function and variables are ommitted here.
}#endif
我很确定命名空间没问题,因为我可以编写 std cin 和 cout。
我的 cpp 实现文件是这样的:
#include <string>
#include <cstdlib>
#include <iostream>
#include "employee.h"
using namespace std;
namespace employeessavitch
{
Employee::Employee( ) : name("No name yet"), ssn("No number yet"), net_pay(0)
{
//deliberately empty
}
}
和
#include <iostream>
#include <string>
#include "salariedemployee.h"
using namespace std;
namespace employeessavitch
{
SalariedEmployee::SalariedEmployee( ) : Employee( ), salary(0)
{
//deliberately empty
}
SalariedEmployee::SalariedEmployee(string the_name, string the_number, double the_weekly_salary): Employee(the_name, the_number), salary(the_weekly_salary)
{
//deliberately empty
}
}
最佳答案
我相信 Employee 构造函数没有声明为类定义的一部分。
在 employee.h 中试试这个:
namespace employeessavitch
{
class Employee
{
public:
Employee( );//default constructor
Employee(string the_name, string the_ssn); //constructor about name and ssn
};
}
关于c++ - 类继承 : Constructor and member functions of class not recognized by compiler,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20158645/