我有几个简单的课程,我无法让他们工作.
TL; DR我有一个"播放器"实例,在我将一些数据设置到实例后,我可以将其恢复.如果我将实例推送到std :: vector Players; 如果我有Players.at(0).getName()则返回"".数据不存在!离开了.(调试应用程序,我在"vPlayer"和"Players"中设置"_name",我看到一个元素,"_ name"="")
这是代码:
//Player.h
#ifndef PLAYER_H
#define PLAYER_H
#include <iostream>
class Player
{
public:
Player();
Player(const Player &Player);
Player& operator=(const Player &Player);
std::string getName();
bool setName(const std::string &name);
bool nameValid(const std::string &name);
private:
std::string _name;
};
#endif
//Player.cpp
#include "Player.h"
#include <iostream>
#include <string>
using namespace std;
Player::Player()
{
}
Player::Player(const Player &Player)
{
}
Player& Player::operator=(const Player &Player) {
return *this;
}
std::string Player::getName()
{
return this->_name;
}
bool Player::setName(const std::string &name)
{
if ( ! this->nameValid(name) )
{
return false;
}
this->_name = name;
return true;
}
bool Player::nameValid(const std::string &name)
{
return name.empty() == false;
}
//Map.h
#ifndef MAP_H
#define MAP_H
#define MAP_X 40
#define MAP_Y 40
#include "Player.h"
#include "Point.h"
#include <vector>
class Map
{
public:
Map();
bool movePlayer(Player &Player, Point &Point);
std::vector<Player> getPlayers();
private:
};
#endif //MAP_H
//Map.cpp
#include "Map.h"
#include "Player.h"
#include "Point.h"
#include <iostream>
#include <string>
using namespace std;
Map::Map()
{
}
bool Map::movePlayer(Player &Player, Point &Point)
{
return true;
}
std::vector<Player> Map::getPlayers()
{
Player vPlayer;
vPlayer.setName(std::string("test"));
std::vector<Player> Players;
Players.push_back(vPlayer);
return Players;
}
Run Code Online (Sandbox Code Playgroud)
在主要:
std::vector<Player> Players = vMap.getPlayers();
cout<<"Test:"<<Players.at(0).getName()<<endl;
Run Code Online (Sandbox Code Playgroud)
Rei*_*ica 10
您可以定义类的复制构造函数和复制赋值运算符以不执行任何操作.您如何期望向量中的副本与放入向量的实例具有相同的数据?
使用默认的,编译器生成的复制构造函数和复制赋值运算符,您的类可以完全正常,因此只需删除它们的声明和定义,一切都会正常工作.