打印一个变量将打印另一个变量的值(以 C++ 为单位)
Printing one variable prints the value of the other variable (in C++)
我最近开始学习C++。今天我想做一个有x和y位置的演示"玩家"类。
我不确定我的方法是否正确,但我担心的是当我打印 (x, y( int 时,它被打印为 (y,x(。
玩家.h :
#pragma once
#include <string>
#include <iostream>
// CLASS -----------------------------------------------------------------
class Player {
private :
std::string name;
float x, y;
const int SPEED = 5;
public:
Player() : x(0) , y(0) {
}
float* getX() {
return &x;
}
float* getY() {
return &y;
}
std::string getName() {
return name;
}
void setX(float block) {
x = block;
}
void setY(float block) {
y = block;
}
void move( float* axis , int direction) {
*axis += direction * SPEED;
}
void setName(std::string block) {
name = block;
}
};
//------------------------------------------------------------------------
std::string getInput(std::string value) {
std::string temp;
std::cout << "Enter "<< value <<" : ";
std::cin >> temp;
std::cout << std::endl;
return temp;
}
玩家.cpp :
#include "Player.h"
int main() {
Player p1;
std::string axis;
int dir;
float* yAxis = p1.getY();
float* xAxis = p1.getX();
p1.setName(getInput("name"));
std::cout << "Your name is " << p1.getName() << std::endl;
std::cout << "Enter 'y' to move in y axis , 'x' to move in x axis : ";
std::cin >> axis;
std::cout << "Enter a positive / negative value for the direction";
std::cin >> dir;
if (axis.compare("y")) {
if (dir < 0) {
p1.move(yAxis, -1);
}
else {
p1.move(yAxis, 1);
}
}
else if (axis.compare("x")) {
if (dir < 0) {
p1.move(xAxis, -1);
}
else {
p1.move(xAxis, 1);
}
}
std::cout << "Position ( " << *xAxis << " , " << *yAxis << " )" << std::endl;
getInput("anything to exit");
}
有人可以回答我哪里出错了吗?
如果字符串相等,std::string::compare
返回 0!
这与你的期望相反。
用axis == "y"
&c 替换会更具可读性,尽管从性能角度来看有更好的方法来实现这一目标。
相关文章:
- std::cout 在打印变量与函数表达式时的行为不同
- 面临在 if 语句之外打印变量数据的问题 完成使用 Qt 编程
- 如何在咖啡中Forward_gpu期间打印变量
- 如何使用类中的函数从 main 打印变量,帮助理解 OOP c++
- 当我在循环内打印变量时无限输出
- 如何打印变量的第一个输入/值?C
- gdb在选项卡完成的情况下打印变量时冻结
- 打印变量的地址
- 试图在C++中打印变量int会导致它崩溃.为什么?
- 有没有一种方法可以在Netbeans中的断点处打印变量的值
- 以十进制打印变量的地址
- WxWidgets 绘制文本以在屏幕上打印变量
- 尝试打印变量.程序崩溃
- 为什么 cout 不打印变量"C"外部?
- 串行打印变量在特定的时间间隔打印数组的大小,即使数组没有被使用
- 在#define中打印变量名
- 我们可以说cout只打印变量的第一个地址吗
- 不能在c++中打印变量a
- 如何使用内存地址打印变量的值
- 没有宏的c++简单反射:打印变量名及其值