我剛剛遇到了類繼承的代碼:構造函數無法被編譯器識別。任何成員函數都不是。 例如,如果我調用構造函數, 我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.cpp和SalariedEmployee.cpp正確鏈接 – billz