我只是遇到了类继承代码的麻烦:编译器无法识别构造函数。也不是任何成员函数。例如,如果我调用构造函数,我的testfile(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
};
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句