【发布时间】:2017-11-10 13:30:02
【问题描述】:
我是 C++ 新手,想玩转类。
我的代码
在我的世界里有英雄和剑。英雄携带剑。这应该不会太难。
// Defining swords
class Sword
{
// The most important thing about a sword is its length.
int lenght;
public:
// only constructor and destructor
Sword(int swordlength){
lenght = swordlength;
};
~Sword(){};
};
// defining heros (as people with magic swords)
class Hero
{
Sword magic_sword;
public:
// each hero gets a standard sword
Hero(){
int meters = 2;
magic_sword = Sword(meters);
};
~Hero(){};
};
int main(){
return 0;
}
编译器是怎么想的
当我编译这段代码 (g++ hero.cpp) 时出现错误:
In constructor 'Hero::Hero()':
20:9: error: no matching function for call to 'Sword::Sword()'
20:9: note: candidates are:
8:3: note: Sword::Sword(int)
8:3: note: candidate expects 1 argument, 0 provided
2:7: note: constexpr Sword::Sword(const Sword&)
2:7: note: candidate expects 1 argument, 0 provided
我认为问题是什么
用clang++编译代码也失败了,但是错误信息不是很明确,所以这里就不贴了。
似乎调用构造函数 Sword(meters) 失败了,因为我提供了 0 而不是 1 参数。但是我清楚地给了它一个论据(meters),所以我想我在这里误解了一些东西。
我的错误是什么,我能做些什么?
【问题讨论】:
-
Hero() : magic_sword(2) { /* 你的 ctor */ } .建造英雄时需要建造剑。当它进入 ctor 中的代码时,Hero 字段已经构建好了。
标签: c++ class constructor