问题描述
我仍然对指针感到困惑,也许你可以告诉我一些。
我有一些类指向对方,没有得到以正确的方式访问它们。
#include< vector>
#include< iostream>
class Player;
class Trainer;
class Team {
Trainer * trainer_;
std :: vector< Player *> player_;
public:
std :: vector< Player *> player(); {return player_; }
Trainer * trainer(){return trainer_; }
std :: vector& lt; Player *> get_playerlist(){
return player_;
};
};
class Player {
public:
void setteam_(Team * x){
team_ = x;
}
private:
Team * team_;
};
类培训师{
Team * Team_;
};
int main()
{
玩家player1;
团队team1;
std :: vector< Player *>播放器列表
player1.setteam _(& team1);
playerlist = team1.get_playerlist();
std :: cout<< playerlist.size();
std :: cin.get();
return 0;
}
主要有player1创建并分配给team1的播放器列表他应该以某种方式出现在那里,当我得到播放器列表。但是这个代码的输出是1号球员的播放器列表的大小仍然为0.我做错了什么?
player1.setteam _(& team1);接下来会发生什么:
<$ p
$ b void setteam_(Team * x){
team_ = x;
}
这里你说这个 c $ c>有指向
Team
的指针设置为与 x
相同的地址。但这并不意味着 Team
对象在 std :: vector
中有指向玩家的指针。这不是自动发生的,你需要类似的:
void setteam_(Team * x){
team_ = X;
x-> addPlayer(this); // add to vector
}
I'm still confused with pointers, maybe you could enlighten me a bit.
I'm having some classes pointing to each other and don't get the way to access them in the right way.
#include <vector>
#include <iostream>
class Player;
class Trainer;
class Team {
Trainer* trainer_;
std::vector<Player*> player_;
public:
std::vector<Player*> player() { return player_; }
Trainer* trainer() { return trainer_; }
std::vector<Player*> get_playerlist(){
return player_;
};
};
class Player {
public:
void setteam_(Team* x){
team_ = x;
}
private:
Team* team_;
};
class Trainer {
Team* Team_;
};
int main()
{
Player player1;
Team team1;
std::vector<Player*> playerlist;
player1.setteam_(&team1);
playerlist = team1.get_playerlist();
std::cout << playerlist.size();
std::cin.get();
return 0;
}
In the main there is player1 created and assigned to the playerlist of team1, now he should somehow appear there when i get the playerlist. But the output of this code is that the size of the playerlist of team 1 is still 0. What did I do wrong ?
player1.setteam_(&team1);
What happens next is:
void setteam_(Team* x){
team_ = x;
}
Here you are stating that this Player
has pointer to Team
set to the same address as x
. But this doesn't mean that this Team
object has pointer to player in std::vector
. This doesn't happen automaticly, you need something like:
void setteam_(Team* x){
team_ = x;
x->addPlayer( this); // add to vector
}
这篇关于使用指针访问对象的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!