2012-04-26 59 views
0

當我在派生層次結構的類中嘗試兩種形式的構造函數時,結果證明是不同的。有誰能告訴我爲什麼?以下是測試代碼。默認類構造函數的兩種形式是否等價?

//Person.h

#ifndef PERSON_H_ 
#define PERSON_H_ 
#include<string> 

using std::string; 

class Person{ 
    private: 
     string firstname; 
     string lastname; 
    public: 
     Person(const char *fn="NoName", const char *ln="NoName"); //A 
     Person(const string &fn, const string &ln); 
     virtual ~Person(){} 

}; 

class Gunslinger:virtual public Person{ 
    private: 
     int notchnum;  
    public: 
     Gunslinger(const char*f="unknown",const char*n="unknown",int not=0);//B 
     virtual ~Gunslinger(){} 
}; 

class PokerPlayer:virtual public Person{ 

    public: 
     PokerPlayer(const char*fn="unknown", const char*ln="unknown");//C; 
     virtual ~PokerPlayer(){} 
};  

class BadDude:public Gunslinger,public PokerPlayer{ 
    public: 
     BadDude(const char*fn="unknown", const char*ln="unknown", int notc=0);//D 

}; 

#endif 

//PersonDefinition.cpp

#include"Person.h" 
#include<iostream> 
#include<cstdlib> 

using std::cout; 
using std::endl; 
using std::cin; 

Person::Person(const char*fn, const char*ln):firstname(fn),lastname(ln){ 
} 

Person::Person(const string &fn,const string &ln):firstname(fn),lastname(ln){ 

} 

Gunslinger::Gunslinger(const char*fn,const char*ln, int not):Person(fn,ln),notchnum(not){ 
} 

PokerPlayer::PokerPlayer(const char*fn,const char*ln):Person(fn,ln){ 
} 

BadDude::BadDude(const char*fn, const char*ln, int notc):Person(fn,ln),PokerPlayer(fn, ln),Gunslinger(fn,ln,notc){ 

} 

//PersonTest.cpp

#include<iostream> 
#include "Person.h" 

int main(){ 
    Person a("Jack","Husain"); 
    PokerPlayer b("Johnson","William",8); 
    Gunslinger c("Mensly","Sim"); 

} 

所以,這裏的問題。上面的程序無法使用默認構造函數對所有參數使用默認值進行編譯,並在「!」之前拋出錯誤消息,說明「expected」,「或」...「令牌「,但如果我將行A,B,C,D中的默認構造函數替換爲不帶參數的形式,程序將編譯並運行成功。請問任何人都可以告訴我爲什麼?以下是錯誤消息。

error message

回答

1

你沒有實現所有構造函數。例如,你聲明瞭一個構造函數PokerPlayer::PokerPlayer(char*, char*),但是你試圖創建一個帶有PokerPlayer b("Johnson","William",8);的PokerPlayer(即你從未聲明過一個構造函數,它接受了第三個參數)。您希望上一行的聲明是PokerPlayer::PokerPlayer(char*, char*, int);

此外,在嘗試聲明GunSlinger時,您會遇到完全相反的問題。你的GunSlinger類需要第三個參數,你試圖在沒有這個參數的情況下聲明它。儘管你的基類支持幾種類型的構造函數,但每個派生類還必須擁有你希望在其上顯式聲明/實現的每個構造函數(默認構造函數除外)。

編輯

下面是一些半功能代碼:

class PokerPlayer : public Person 
{ 
    ... 
    PokerPlayer(char* fname, char* lname, int val); 
    ... 
}; 

實施

PokerPlayer::PokerPlayer(char* fname, char* lname, int val) : Person(fname, lname, val) 
{ 
    // Anything else we should do... 
} 
+0

我根據您的意見修改了代碼,但該方案仍無法編譯,在「!」之前拋出諸如「expected」,「或」之類的錯誤信息。令牌「和」預期的主要表達式之前「)」令牌「。沒有感嘆號。 – JDein 2012-04-26 15:34:02

+0

我用一些功能代碼更新了我的示例,以瞭解它的外觀。 – RageD 2012-04-26 15:39:03

+0

我有另一個問題。上面的代碼使用VS2010編譯成功,但無法使用昨天使用的IDE進行編譯。爲什麼這樣? – JDein 2012-04-27 06:45:36

相關問題