c++ error C2512:没有合适的默认构造函数可用

这是我最近学习c++过程中遇到的一个问题,同时也说明了自定义类的使用,这里借用别人的例子来说明一下这个问题。

 

View Code
 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<<""<endl;
60 };

 

 

  

注释掉Weapon的void构造函数会提示error C2512: “Weapon”: 没有合适的默认构造函数可用。

 

1、由于你在Weapon中定义了其他构造函数,那么,编译器不会为你创建默认构造函数;然而,你在Actor的构造函数中没有调用Weapon的构造函数,那么,编译器会调用Weapon的默认构造函数,然而,却没有定义,所以,产生了“error C2512: “Weapon”: 没有合适的默认构造函数可用”错误!

转载于:https://www.cnblogs.com/ITEagle/archive/2012/10/10/2718012.html

你可能感兴趣的:(c++ error C2512:没有合适的默认构造函数可用)