你好,我想做一个有点像口袋妖怪的游戏,但是我被打印统计数据困住了。 我试图用它输出一个水平,显示动物达到了什么水平。
对我没有得到预期结果有什么帮助吗?
我的代码:
VisualAnimal.h(尚未使用):
#include <string>
#ifndef VISUALANIMAL_H
#define VISUALANIMAL_H
using namespace std;
using namespace Animals;
/*** Visual based on original class
@author Adam Petla
***/
class VisualAnimal : Animal {
public:
string imageFileURL;
int size;
VisualAnimal() {
this->imageFileURL = "";
this->size = 0;
}
};
#endif
动物。H:
#include <string>
#include <stdio.h>
#include <iostream>
#ifndef ANIMAL_H
#define ANIMAL_H
using namespace std;
namespace Animals {
class Animal {
public:
string name;
int minlevel;
int level;
int maxlevel;
int baseattack;
int baseattackraise;
int attack;
int basedefense;
int basedefenseraise;
int defense;
int basespeed;
int basesppedraise;
int speed;
int basespecial;
int basespecialraise;
int special;
char type;
Animal() {
name = "DOG";
minlevel = 0;
level = 1;
maxlevel = 100;
baseattack = 1;
baseattackraise = 1;
basedefense = 1;
basedefenseraise = 1;
basespecial = 1;
basespecialraise = 1;
basespeed = 1;
basesppedraise = 1;
};
private:
void printstats() {
//cout << "Attack : " << this->
};
void raiseattack() {
this->attack += this->baseattackraise;
}
void raisedefense() {
this->defense += this->basedefenseraise ;
}
void raisespeed() {
this->speed += this->basesppedraise;
}
void raisespecial() {
this->special += this->basespecialraise;
}
void raisestats() {
raiseattack();
raisedefense();
raisespeed();
raisespecial();
}
void updatestats(char type) {
switch (type) {
case 'l':
raisestats();
}
}
public :
void raiselevel() {
this->level++ ;
this->type = 'l';
updatestats(this->type);
string output = "Level Up!Your " + string(this->name) + string("has reached level");
cout << output;
cout << this->level + ".Its stats are now";
printstats();
};
};
}
#endif
animal.cpp:
// Animals.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <iostream>
#include "animal.h"
#include "visualanimal.h"
using namespace std;
int main()
{
using namespace`` Animals;
Animal test;
test.raiselevel();
cout << "Hello World!\n";
return -1;
}
我的预期结果:狗达到2级。 我的实际结果狗达到水平,任何人知道一个答案,它没有显示任何水平的输出,任何人知道为什么?
+
的优先级高于<<
,因此行cout<<<; 此->级别+“。其stats are now”;
计算为cout<<;<; (this->level+“。its stats are now”);
-level
的值被用作字符串文本“的偏移量。它的stats now是”
,这不是您想要的。
将其更改为
cout << this->level << ".Its stats are now";
或者在此查看如何将int
与string
连接起来。
更改以下内容:
cout << this->level + ".Its stats are now";
致:
cout << this->level << ".Its stats are now";
由于您试图将string
和int
串联起来,因此得到了不正确的输出。
将字符串连接到int
的正确方法是使用std::to_string()
:
int val = 2;
std::string x = "hello";
std::string output = std::to_string(val) + x;
想出了为什么不起作用。 感谢@Rustyx,他说+的优先级比<<<. 我的成绩现在和预想的一样。