0$房天下问答|c++面向对象的小问题$https://m.fang.com/ask/ask_1799400.html$https://static.soufunimg.com/common_m/m_public/201511/images/asksharedefault.png
packc/pages/ask/detail/detail?askid=1799400
-
c++面向对象的小问题
# include <iostream>#include<string>using namespace std; class boss{ public: string name; int hp; int mp; int dps; boss(char _name,int _hp){ name=_name; hp=_hp; dps=5; } void kill(){ cout<<"kill is done"; } void hit(){ cout<<"yourHp decrease"<<dps; } int displayHp(){ return hp; }};void main(){ boss a("dog",100); a.hit; a.kill;}1>------ 已启动生成: 项目: 111, 配置: Debug Win32 ------1>正在编译...1>work.cpp1>.\work.cpp(27) : error C2664: “boss::boss(char,int)”: 不能将参数 1 从“const char [4]”转换为“char”1> 没有使该转换得以执行的上下文1>.\work.cpp(28) : error C3867: “boss::hit”: 函数调用缺少参数列表;请使用“&boss::hit”创建指向成员的指针1>.\work.cpp(29) : error C3867: “boss::kill”: 函数调用缺少参数列表;请使用“&boss::kill”创建指向成员的指针1>生成日志保存在“file://d:\我的文档\Visual Studio 2008\Projects\111\111\Debug\BuildLog.htm”1>111 - 3 个错误,0 个警告========== 生成: 成功 0 个,失败 1 个,最新 0 个,跳过 0 个 ==========问题1c++可不可以像Java一样把类的方法写在类的里面?问题2我明明定义了STRING类型,怎么还说我传的DOG有问题?问题3c++里调用方法可以写 对象.方法 么?还是必须用指针什么的?刚学c++,大家见笑了。
更多
共1个回答
-
-
-
yjhy2008
丨Lv 4
把你的代码改了下:# include <iostream> #include<string> using namespace std; class boss{ public: string name; int hp; int mp; int dps; boss(char *_name,int _hp){ //这里要改为传入一个字符数组或者是一个string,按你原来的写法只能传入一个字符name=_name; hp=_hp; dps=5; } void kill(){ cout<<"kill is done"<<endl; } void hit(){ cout<<"yourHp decrease: "<<dps<<endl; } int displayHp(){ return hp; } }; void main(){ boss a("dog",100); a.hit(); //你原来调用方法的时候都少写了小括号了,所以报错了。现在帮你加回去了a.kill(); } 回答你的问题:问题1:可以问题2:因为你定义的传值参数不对。你在构造函数里只是传入一个'char'数值,但是"dog"是一个字符串或者说是一个"char"数组,所以就出错了。我帮你改成传入一个字符头指针问题3:C++里的调用方法可以写 对象.方法,也可以用 指针->方法。不过你要注意你书写函数的格式,上面你调用方法的时候少写了小括号了。
免责声明:问答内容均来源于互联网用户,房天下对其内容不负责任,如有版权或其他问题可以联系房天下进行删除。

关注成功