【发布时间】:2020-02-04 00:56:49
【问题描述】:
我最近开始学习 c++,在我的一生中,我似乎无法理解在 class 中使用 ostream 的语法以及我应该传递哪些参数。代码如下:
这是有问题的课程:
#include <iostream>
#include <string>
using namespace std;
class Pokemon{
friend ostream& operator<<(ostream&, Pokemon);
public:
string name, level, cp;
Pokemon(string x="Pikachu", string y="5", string z="1000"){
name = x;
level = y;
cp = z;
}
Pokemon name(){
return this->name;
}
Pokemon level(){
return this->level;
}
Pokemon cp(){
return this->cp;
}
Pokemon display_stats(){
cout << this-> name << "stats are:" << endl;
cout << " " << "Attack: 2716.05" << endl;
cout << " " << "Defence: 1629.63" << endl;
cout << " " << "HP: 1086.42" << endl;
}
};
template<typename TYPE> //i dont understand this and the things i've written down here are only based on samples i've seen
ostream& operator<<(ostream& os, Pokemon & c){
os << "The level of " << c.name << " is" << c.level << " with cp of " << c.cp;
}
如您所见,我已经尝试构建 ostream 东西,但我并不真正了解它是如何工作的。这是我的主要功能:
int main()
{
Pokemon a, b, c, d;
a = Pokemon();
b = Pokemon("Weezing");
c = Pokemon("Nidoking", 100);
d = Pokemon("Mewtwo", 50, 5432.1);
cout << a << endl;
cout << b << endl;
cout << c << endl;
cout << d << endl;
cout << "Jessie: You are no match to me! Go " << b.name << "!" << endl;
cout << "Gary: Go lvl " << c.level << " " << c.name << "! Crush them" << endl;
cout << "Ash: " << a.name << " can do it even thouh he is only level " << a.level << endl;
cout << "Jessie: Hahaha! My " << b.name << " CP is " << b.cp << endl;
cout << "Gary: "<< c.name << " CP is " << c.cp << endl;
cout << "Ash: " << a.name << " CP is " << a.cp << endl;
cout << "Giovanni: Behold " << d.name << " is here." << endl;
d.display_stats();
return 0;
}
我收到以下错误:
no instance of constructor "Pokemon::Pokemon" matches the argument list -- argument types are: (const char [9], int) //on line c = Pokemon("Nidoking", 100);
no instance of constructor "Pokemon::Pokemon" matches the argument list -- argument types are: (const char [7], int, double) //on line d = Pokemon("Mewtwo", 50, 5432.1);
【问题讨论】:
-
C++ 语言不是 C#。
-
您需要重新访问您最喜欢的参考资料或获取新的参考资料。为什么
name方法返回整个Pokemon对象?它应该返回std::string吗? -
您的
display_status功能所在。函数声明说它应该返回一个Pokemon实例,但display_status函数不返回任何内容。 -
operator<<的定义之前不需要template行。在您更好地掌握该语言之前,请忘记模板。经验法则:模板适用于数据类型发生变化但算法相同的情况。 -
关于ostream:您需要返回ostream对象,以便可以将多个调用链接在一起。这就是返回 ostream 对象的目的。