您的位置:首页 > 编程语言 > C语言/C++

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

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

View Code

#include "stdafx.h"
using namespace std;

/* --- --- --- --- --- --- --- 武器类 --- --- --- --- --- --- */
class Weapon
{
private:
string name;
int power;
public:
void Show();
//Weapon(){};
Weapon(string name,int power);
};

Weapon::Weapon(string name, int power)
{
this->name = name;
this->power = power;
};

void Weapon::Show()
{
cout<<"武器名:"<<this->name<<"威力值:"<<this->power<<endl;
};

/* --- --- --- --- --- --- --- 角色类 --- --- --- --- --- --- */

class Actor
{
private:
string name;
bool gender;
Weapon weapon;
public:
Actor(string name, bool gender);
void Say();
void Say(string message);
void SetWeapon(Weapon &weapon)
{
this->weapon = weapon;
}
};

Actor::Actor(string name, bool gender)
{
this->gender = gender;
this->name = name;
}

void Actor::Say()
{
cout<<"我乃"<<this->name<<"是也..."<<endl;
};

void Actor::Say(string message)
{
cout<<this->name<<":"<<message<<endl;
};


  

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

1、由于你在Weapon中定义了其他构造函数,那么,编译器不会为你创建默认构造函数;然而,你在Actor的构造函数中没有调用Weapon的构造函数,那么,编译器会调用Weapon的默认构造函数,然而,却没有定义,所以,产生了“error C2512: “Weapon”: 没有合适的默认构造函数可用”错误!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: