這是我最近學習c++過程中遇到的一個問題,同時也說明了自定義類的使用,這里借用別人的例子來說明一下這個問題。

1 #include "stdafx.h" 2 using namespace std; 3 4 /* --- --- --- --- --- --- --- 武器類 --- --- --- --- --- --- */ 5 class Weapon 6 { 7 private: 8 string name; 9 int power; 10 public: 11 void Show(); 12 //Weapon(){}; 13 Weapon(string name,int power); 14 }; 15 16 Weapon::Weapon(string name, int power) 17 { 18 this->name = name; 19 this->power = power; 20 }; 21 22 void Weapon::Show() 23 { 24 cout<<"武器名:"<<this->name<<"威力值:"<<this->power<<endl; 25 }; 26 27 28 /* --- --- --- --- --- --- --- 角色類 --- --- --- --- --- --- */ 29 30 class Actor 31 { 32 private: 33 string name; 34 bool gender; 35 Weapon weapon; 36 public: 37 Actor(string name, bool gender); 38 void Say(); 39 void Say(string message); 40 void SetWeapon(Weapon &weapon) 41 { 42 this->weapon = weapon; 43 } 44 }; 45 46 Actor::Actor(string name, bool gender) 47 { 48 this->gender = gender; 49 this->name = name; 50 } 51 52 void Actor::Say() 53 { 54 cout<<"我乃"<<this->name<<"是也..."<<endl; 55 }; 56 57 void Actor::Say(string message) 58 { 59 cout<<this->name<<":"<<message<<endl; 60 };
注釋掉Weapon的void構造函數會提示error C2512: “Weapon”: 沒有合適的默認構造函數可用。
1、由於你在Weapon中定義了其他構造函數,那么,編譯器不會為你創建默認構造函數;然而,你在Actor的構造函數中沒有調用Weapon的構造函數,那么,編譯器會調用Weapon的默認構造函數,然而,卻沒有定義,所以,產生了“error C2512: “Weapon”: 沒有合適的默認構造函數可用”錯誤!