打印一个变量将打印另一个变量的值(以 C++ 为单位)

Printing one variable prints the value of the other variable (in C++)

本文关键字:打印 变量 C++ 为单位 另一个 一个      更新时间:2023-10-16

我最近开始学习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 替换会更具可读性,尽管从性能角度来看有更好的方法来实现这一目标。