【问题标题】:How can I get the created object of the class that is constructed in main() function?如何获取在 main() 函数中构造的类的创建对象?
【发布时间】:2020-09-25 13:03:29
【问题描述】:

我想获取在 main() 函数中构造的类的对象,并在另一个类中使用这个对象。

这是我要取它的对象的类:

typedef enum {
    DOWN = 1,
    LEFT = 2,
    UP = 3,
    RIGHT = 4
} tWaypointDir;

class Waypoint
{
    sf::Texture texture;
    sf::Sprite sprite;

public:
    float x, y;
    int dir;
    int next1, next2, next3;

    Waypoint(tWaypointDir dir, tRoadTileType type, int row, int col, int idx, int next1, int next2, int next3); // Constructor for the class.
    // idx: internal index of the waypoints, next1, 2, 3: next waypoints of the current one.
    // if there is only next1, next2 and next3 are -1. 
    int getNext(); //Get next waypoint randomly
    void getPosition(float &x, float &y, float &dir) const { x = this->x; y = this->y; dir = this->dir; }
    void setPosition(float x, float y, float dir) { this->x = x; this->y = y; this->dir = dir; }
    void draw(sf::RenderWindow *window) {window->draw(sprite);}
};

我在main()函数中创建的对象是:

Waypoint waypoints[] = { //CTL: Road at top-left, HOR: horizontal, etc..
    {UP, CTL, 0, 0, 0, 1, -1, -1}, {RIGHT, CTL, 0, 0, 1, 0, -1, -1},
    {RIGHT, HOR, 0, 1, 0, 3, -1, -1}, {RIGHT, HOR, 0, 1, 1, 2, -1, -1},
    {RIGHT, TTOP, 0, 2, 0, 5, 6, -1}, {DOWN, TTOP, 0, 2, 1, 4, 6, -1},
    {RIGHT, TTOP, 0, 2, 2, 4, 5, -1}, {RIGHT, HOR, 0, 3, 0, 8, -1, -1}
};

现在,在 Car 类中,我想使用 waypoints[] 对象,因为我将汽车朝航点的方向移动。我在这个类中有一个 move() 函数,我在那部分使用了这个对象。我们不允许在 main() 函数中进行移动。因此,我必须在课堂上实现这一点。

我在 Waypoint 类上尝试了 Singleton 设计模式,但它在构造函数部分给了我错误。如何在 Car 类上实现这一点?

【问题讨论】:

    标签: c++ oop c++11 sfml


    【解决方案1】:

    您可以将Waypoint 类上的指针或引用作为Car 类构造函数或方法中的参数传递。 Car 类可以将此引用或指针存储为成员。然后就可以从Car类访问这个对象了

    【讨论】:

    • 作为引用或指针传递之间存在差异。它们之间有什么区别?我使用了问题中所述的数组对象,所以可能我无法传递指针。
    • @Utku,区别在于用法。你不能在没有初始化它的值的情况下声明引用,也不能改变引用赋值,它总是引用它被初始化引用的值。使用指针你可以做任何你想做的事情,你只需要确保它指向有效的内存块。你可以在你的情况下使用指针。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-10
    • 1970-01-01
    • 2020-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-02
    相关资源
    最近更新 更多