I can not return the name

2

I am trying to get a method of a class to return a string that has been entered through the keyboard, showing it in a cout. However, I'm doing something wrong, because even though the program compiles I can not show the introduced string. Still my IDE gives me the following notice:

  

Assign return value to new variable

I guess it will be silly but I've been stuck for a while and can not think of anything. Here is the code.

Player.h
#ifndef PLAYER_H
#define PLAYER_H
#include <string>

class Player{
public:
  Player(std::string name, int health, int damage);

      void setName(std::string name);
      std::string getName() const;

      void setHealth(int health);
      int getHealth() const;

      void setDamage(int damage);
      int getDamage() const;
  private:
   std::string name;
   int health;
   int damage;
 };  
  #endif /* JUGADOR_H */
Player.cpp
#include "Player.h"

Player::Player(std::string name, int health, int damage){
setName("default");
setHealth(100);
setDamage(30);
 }

void Player::setName(std::string name)
{
name = name;
}

void Player::setHealth(int health){

health = 100;
}

void Player::setDamage(int damage){

damage = 30;
}

std::string Player::getName() const{

return name;

}

int Player::getHealth() const{

return health;
}

int Player::getDamage() const{

return damage;

}

I have problems to insert the complete code, so here I leave the github where I have it up to make it look better:

Player.cpp

main.cpp

main.cpp

#include <cstdlib>
#include "Player.h"
#include "Monster.h"
#include <iostream>
#include <string>



int main(int argc, char** argv) {
std::string name;
std::cout <<"Hello! Write your name "<<std::endl;
getline(std::cin, name);
Player player(name, 100, 30);
std::cout <<"Welcome "<<player.getName();
}
    
asked by JACK1ETO 14.06.2018 в 10:53
source

1 answer

3

You are doing a self-assignment:

void Player::setName(std::string name)
{
    name = name;
}

Change the name of the parameter:

void Player::setName(std::string otro_name)
{
    name = otro_name;
}

Or disambiguate with this :

void Player::setName(std::string name)
{
    this->name = name;
}
    
answered by 14.06.2018 / 11:26
source