c++ error C2512:没有合适的默认构造函数可用
这是我最近学习c++过程中遇到的一个问题,同时也说明了自定义类的使用,这里借用别人的例子来说明一下这个问题。#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”: 没有合适的默认构造函数可用”错误!
页:
[1]