Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
Using the example below, I would like to call the function printTop() from my 'Bottom' object. It seems perhaps I could use a pointer to the parent object?
class Bottom {
public:
void printBottom(){std::cout << "print bottom";};
};
class Top {
public:
void printTop(){std::cout << "print top";};
private:
Bottom bottom;
};
Thanks.
If this is truly where your heart is at, it can be done (doesn't mean i'd advocate it):
class Top;
class Bottom {
public:
Bottom( const Top& topLevelObj ) : _topLevelObj(topLevelObj) { }
void printBottom() const {std::cout << "print bottom";};
void printTop() const;
private:
const Top& _topLevelObj;
};
class Top {
public:
Top() : _bottom(*this) {}
void printTop() const {std::cout << "print top";};
private:
Bottom _bottom;
};
void Bottom::printTop() const { _topLevelObj.printTop(); }
Firstly your code will not execute due to an error in your code, figure it out.
Secondly, you cannot call function printTop() from your Bottom object because you have no access to printTop() from the Bottom class.
You could maybe rewrite the code in this way:
class Top {
public:
void printTop(){ std::cout << "print top"; }
};
class Bottom {
public:
void printBottom(){ std::cout << "print bottom"; }
Top top;
};
int main()
{
Bottom B;
B.top.printTop();
return 0;
}
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
As the title says when I run my program, visual studio, give me that error. The class that produce that error is the following:
class UsesScene {
BaseScene & scene;
public:
UsesScene(BaseScene& scene) : scene(scene) {}
void Start() { scene.Start(); }
void EventHandler(SDL_Event ev) { scene.EventHandler(ev); }
void Update() { scene.Update(); }
void Draw(SDL_Renderer* renderer) { scene.Draw(renderer); }
};
The popup appears after } at the end of the initialization of the Start void.
Another code that can interact with these classes is the following:
void GameManager::regScene(UsesScene scene) {
if (display != NULL) {
UsesScene* ptr = &scene;
UsesScene** pptr = &ptr;
display = *pptr;
}
else
{
UsesScene* ptr = &scene;
UsesScene** pptr = &ptr;
buffer = *pptr;
}
}
the display & buffer are declared as
class GameManager
{
private:
SDL_Window* window;
SDL_Renderer* renderer;
UsesScene* display;
UsesScene* buffer;
bool isRunning;
bool reStart;
};
and for access to the display or buffer's parameter I use the following syntax:
display->Start();
and the last thing that has to do with this class is this part of code:
TestScene tScene;
UsesScene testScene(tScene);
this->regScene(testScene);
Test Scene simply extends BaseScene:
class BaseScene
{
private:
bool sceneloop = false;
public:
virtual void Start() { std::cout << "BasceScene::Start()" << std::endl; };
virtual void EventHandler(SDL_Event event) {};
virtual void Update() {};
virtual void Draw(SDL_Renderer* renderer) {};
void _toggleLoopMode() { sceneloop = !sceneloop; }
bool _sceneloop() { return sceneloop; }
};
How I can solve this?
ps:
some code that doesn't interfere with the Display and Buffer wasn't reported, if you need: free to ask
So, after a few hours of coding, thanks to Remy Lebeau, I've finally resolved this issue.
First I've changed the regScene() method and now looks like this:
void GameManager::regScene(UsersScene *scene) {
if (SceneManager::_display == NULL)
_display = scene;
else
_buffer = scene;
}
And then I pass the scene like this:
TestScene tScene;
UsersScene testScene(tScene);
sManager->regScene(&testScene);
Thanks to all.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I'm writing a cheat for an offline game, and have a class called Player which is responsible for getting and setting values in another process. However, my design for this class is very poor because the use of the class Player looks very messy and ugly, very difficult to read, and maintain
// declare variables here to read
if (Player.getthis() && Player.getthat() && Player.getthat() ... and so on)
//do stuff
class Player {
...
public:
...
// either of these calls can fail, so I return TRUE on success and FALSE on failure
BOOL GetHealth(float& health);
BOOL SetHealth(float& health);
...
};
So my question is, what is a better way of doing this?
Also: I don't necessarily need to read every single value of Player in memory, only a few at a time. That is why I don't have a single method such as BOOL UpdatePlayer() which will read everything and update the player
Here is how I would do it:
class Player {
public:
class AccessException : public std::exception {
friend class Player;
public:
virtual const char *what() const noexcept {
return "Error getting property with key " + key;
}
private:
AccessException(const std::string &key)
: key(key)
{}
std::string key;
};
float GetHealth() {
if (is_error) {
throw AccessException("health");
}
return health;
}
float GetPosX() {
if (is_error) {
throw AccessException("posX");
}
return posX;
}
};
void do_stuff() {
try {
float health = player.GetHealth();
float posX = player.GetPosX();
// Use health and posX...
} catch (const AccessException &ex) {
std::cerr << ex.what() << std::endl;
}
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I'm building an engine. I need to create a Timer class which will call a function by a pointer from a separate class. For example:
class MyTimer {
public:
void setTimeoutFunction( _pointer_, unsigned short timeoutMs ) {
// here we need to have a opportunity to store a _pointer_ to a function
}
void tickTimer() {
...
// here I need to call a function by a pointer
...
}
};
// Main class:
class MyAnyClass {
public:
void start() {
MyTimer myTimer;
myTimer.setTimeoutFunction( startThisFunc, 1500 ); // 1500ms = 1.5s
while ( true ) {
myTimer.tickTimer();
}
}
void startThisFunc() { ... }
}
In summation, how do you store a pointer to a function which belongs to some class and call that function by a pointer?
For your requirements, I might recommend making the timer a class template:
template <typename T>
struct MyTimer
{
using FuncPtr = void (T::*)();
MyTimer(FuncPtr ptr, T * obj, unsigned int timeout_ms)
: ptr_(ptr), obj_(obj), timeout_ms_(timeout_ms) {}
void tickTimer()
{
(obj_->*ptr_)();
}
FuncPtr ptr_;
T * obj_;
unsigned int timeout_ms_;
};
Usage:
struct MyAnyClass
{
void start()
{
MyTimer<MyAnyClass> myTimer(&MyAnyClass::startThisFunc, this, 1500);
while (true) { myTimer.tickTimer(); }
}
void startThisFunc() { /* ... */ }
};
In C++11 you can use std::function. A good guide on using it is here: http://en.cppreference.com/w/cpp/utility/functional/function
I created a new code snippet only containing the case you want.
#include <stdio.h>
#include <functional>
#include <iostream>
struct Foo {
Foo(int num) : num_(num) {}
void print_add(int i) const { std::cout << num_+i << '\n'; }
int num_;
};
int main()
{
// store a call to a member function
std::function<void(const Foo&, int)> f_add_display = &Foo::print_add;
const Foo foo(314159);
f_add_display(foo, 1);
return 0;
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
As a practice program after learning C++, I am developing a text-based game. I am using object-oriented programming style for handling the worlds/their objects. Here's the necessary information about their definitions:
class Object
{
private:
unsigned int id;
public:
unsigned int getID() const { return id; }
};
class TakeableObject: public Object
{
...
};
class EdibleObject: public TakeableObject
{
private:
float healthEffect;
float staminaEffect;
public:
float getHealthEffect() const { return healthEffect; }
float getStaminaEffect() const { return staminaEffect; }
};
class Player
{
private:
float health;
float stamina;
TakeableObject inventory[256];
public:
eat(const EdibleObject* o)
{
health += o->getHealthEffect();
stamina += o->getStaminaEffect();
}
eat(int id)
{
if (inventory[id] == NULL)
throw "No item with that ID!";
eat((EdibleObject) inventory[id]);
inventory[id] = NULL;
}
};
So my question is - in Player::eat(int), is there a way I can make sure the Object at Player::inventory[id] is an EdibleObject (perhaps through exception handling?)
User dynamic cast to check the object type at runtime.
Or you can use a virtual function with default definition in parent and can update it as per your requirement in derived classes.
Instead of eat((EdibleObject) inventory[id]); use the following
EdibleObject *temp = dynamic_cast<EdibleObject *>( &inventory[id] );
if(temp) { eat(*temp); }
else { /* Handling */ }
Your code suffers Object splicing, make sure to get rid of that first.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I want to fill an array that's a member of a class with data. Do I have to create a function that populates it, or is there a way that I can just enter the values directly?
class example
{
private:
struct exm {
int everything[3];
};
public:
exm demo;
void output();
void populate();
};
If not would this work?
void example::populate() {
demo.everything[0] = 1;
demo.everything[2] = 1;
//and so on... (could probably use a for loop)
}
Since demo is a public member you can access it directly or you can create a member function to set values.
#include <iostream>
class example
{
private:
struct exm {
int everything[3];
};
public:
exm demo;
void output();
void populate(){
demo.everything[2] = 1;
}
};
int main()
{
example Test;
Test.demo.everything[0] = 5;
Test.populate();
std::cout<< Test.demo.everything[0]; //outputs 5
std::cout<< Test.demo.everything[2]; //outputs 1
return 0;
}
`