[英]C++ Referencing an objects current state within another object
我一直在尋找這個問題的答案,並嘗試了許多解決方案,包括前向聲明,指針和引用。 我確定我只是在某處使用了不正確的語法。 經過許多小時的浪費之后,我決定轉向堆棧溢出。
我正在嘗試將我的第一個CPP應用程序之一編碼為學習經驗。 現在我有一個Player和一個Ball對象。 我的Ball對象必須能夠訪問我的玩家對象中的某些成員變量和方法。 我一直無法弄清楚該怎么做。 下面是我的代碼的極其簡化的版本。 我評論了特別重要的代碼。
PlayState.hpp
#ifndef PLAYSTATE_HPP
#define PLAYSTATE_HPP
#include "Player.hpp"
#include "Ball.hpp"
class Player;
class Ball;
class PlayState
{
public:
PlayState();
Player player;
Ball ball;
};
#endif
PlayState.cpp
#include "PlayState.hpp"
PlayState::PlayState() {
}
void PlayState::update() {
if (sf::Keyboard::isKeyPressed(sf::Keyboard::W))
{
ball.checkCollision();
player.move(1);
}
ball.update();
}
void PlayState::draw()
{
m_game.screen.clear();
m_game.screen.draw( player.getSprite() );
m_game.screen.draw( ball.getSprite() );
m_game.screen.display();
}
播放器
#ifndef PLAYER_HPP
#define PLAYER_HPP
class Player
{
public:
Player();
~Player();
void create();
void setRotation(float);
void setPosition(float, float);
};
#endif
Player.cpp並不是很重要。
球
#ifndef BALL_HPP
#define BALL_HPP
class Player; // I don't think forward declaration is what I need???
class Ball
{
public:
bool picked_up;
bool throwing;
Player *player; // this isn't working
Ball();
~Ball();
bool checkCollision();
};
#endif
球cpp
#include "Ball.hpp"
Ball::Ball() {
Ball::picked_up = false;
Ball::throwing = false;
}
Ball::~Ball() {
}
bool Ball::checkCollision()
{
float ball_position_x = Ball::getPosition().x;
float ball_position_y = Ball::getPosition().y;
// I need to access the player object here.
float x_distance = abs(player.getPosition().x - ball_position_x);
float y_distance = abs(player.getPosition().y - ball_position_y);
bool is_colliding = (x_distance * 2 < (player.IMG_WIDTH + Ball::width)) && (y_distance * 2 < (player.IMG_HEIGHT + Ball::height));
return is_colliding;
}
當你說player
,你的意思是完全一樣的player
是在同一個playstate
對象作為當前ball
對象? 如果是這樣,您想先設置該鏈接,則無法自動完成。
PlayState::PlayState() :ball(&player){ //pass pointer to ball of its player?
}
class Ball
...
Ball(Player *myPlayer);
...
}
Ball::Ball(Player *myPlayer):player(myPlayer) {
...
// I need to access the player object here.
float x_distance = abs(player->getPosition().x - ball_position_x);
您還需要使用指針來使用播放器,因為它是指向播放器對象的指針。
您確實需要在Ball類上方向Player聲明向前。 高於Playstate的那個是不必要的。
另外,您的播放器似乎沒有GetPosition函數,我假設它是您忘記包含在上面的公共成員函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.