打印一个变量会打印另一个变量的值(在C ++中)

时间:2018-06-04 12:38:59

标签: c++

我最近开始学习C ++。今天我想制作一个具有x和y位置的演示“玩家”类。

我不确定我的方法是否正确,但我担心的是当我打印(x,y)int时,它被打印为(y,x)。

Player.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;
}

Player.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");
}

有人能回答我出错的地方吗?

1 个答案:

答案 0 :(得分:0)

如果字符串相等,

std::string::compare将返回0!

这与您的期望相反。

替换为axis == "y"&amp; c。虽然从性能角度来看有更好的方法可以实现这一点,但它会更具可读性。

相关问题