I have managed to solve this myself by moving the #include for part_time.h to the top of the #include list. Why this made a difference, I have no idea.對象構造函數調用未聲明在此範圍內
我有我的分裂程序轉換成一個makefile後一個手動對象構建呼叫的問題。每個.cpp都有一個包含它的.h,main.cpp也包含每個.h。
相關代碼如下。錯誤是:
main.cpp: In function ‘void add_part_time()’: main.cpp:166:2: error: ‘part_time’ was not declared in this scope part_time part_time1(name, forklift, annual_leave, sick_leave); ^
main.cpp:166:12: error: expected ‘;’ before ‘part_time1’ part_time part_time1(name, forklift, annual_leave, sick_leave);
我注意到了一些奇怪的東西。如果我刪除了;在sick_leave定義行之後,我得到的唯一錯誤是同一個問題關於失蹤的問題;另一個錯誤消失。
#include <string>
using namespace std;
class employee
{
public:
static int count;
employee (std::string name);
string name;
~employee();
};
employee::employee (string set_name)
{
name = set_name;
}
employee::~employee()
{
}
class dockhand: public employee
{
public:
dockhand (string set_name, bool set_forklift);
float start_shift;
bool forklift;
float payrate;
~dockhand();
};
dockhand::dockhand (string set_name, bool set_forklift) : employee (set_name)
{
forklift = set_forklift;
start_shift = 4.00;
}
dockhand::~dockhand()
{
}
class part_time: public dockhand
{
public:
part_time (string set_name, bool set_forklift, int annual_leave, int sick_leave);
float end_shift;
int annual_leave;
int sick_leave;
~part_time();
};
part_time::part_time (string set_name, bool set_forklift, int annual_leave, int sick_leave) : dockhand (set_name, set_forklift)
{
end_shift = 8.00;
payrate = 22.00;
}
part_time::~part_time()
{
}
void add_part_time()
{
string name;
bool forklift;
int annual_leave;
int sick_leave;
name = "bob";
forklift = true;
annual_leave = 2;
sick_leave = 3;
part_time part_time1(name, forklift, annual_leave, sick_leave);
}
然而,完全相同的格式與另一個類編譯得很好。
void add_casual()
{
string name;
bool forklift;
name = "bob";
forklift = true;
casual casual1(name, forklift);
}
我被困在什麼問題。註釋掉構造線會使其編譯,所以它絕對是一些東西。
編輯更改part_time part_time1(name,forklift,annual_leave,sick_leave);行到隨便的構造函數調用使它與一個makefile很好地編譯。所以即使包含正確,該特定行仍然有問題。
[MCVE](http://stackoverflow.com/help/mcve)會真的有所幫助。我得到[完全不同的錯誤](http://coliru.stacked-crooked.com/a/f201f8e68c9e4b8d)。 – chris
在附註上,我認爲最好使用以大寫字母開頭的類名。例如,'class Part_time:public Dockhand'。它使代碼更具可讀性,特別是當你的函數的名字與返回類型相匹配時,比如'part_time part_time1(name,forklift,annual_leave,sick_leave);' –
好吧,我只是把它全部合併到了一塊代碼中,好,但我的生成文件設置仍然給我上面的錯誤。你有什麼想法爲什麼會發生? –