如何获取在 main() 函数中构造的类的创建对象?
How can I get the created object of the class that is constructed in main() function?
我想获取在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类上尝试了单例设计模式,但它在构造函数部分给了我错误。如何在 Car 类上实现这一点?
您可以在类构造函数或方法中将类Waypoint
指针或引用作为参数传递Car
。Car
类可以将此引用或指针存储为成员。然后你可以从类Car
访问这个对象
相关文章:
- 使用基类指针创建对象时,缺少派生类析构函数
- 如何创建对象函数指针C++映射?
- C++创建对象数组
- 在 C++ 的 Switch Case 中创建对象后对对象调用方法
- 如何获取在 main() 函数中构造的类的创建对象?
- 基于文件中的条目创建对象
- 错误:创建对象后无法分配区域
- C++ 通过输入创建对象
- 堆还是堆栈用于创建对象?
- 使用 C++ 创建对象数组
- 使用unique_ptr创建对象
- C++递归地在类构造函数中创建对象
- 通过向构造函数其他对象引用页面来创建对象
- ReactiveX (rx) - 在对象上应用可观察对象,而不是在可观察对象中创建对象
- 如何在OSX上正确创建C++对象文件(.o)
- 编译器是否会创建vtable,而不考虑在c++中创建对象
- C++当我们创建对象时,构造函数会初始化,但是如果我想再次重新初始化对象,请在 main 的某个时候说该怎么做
- 如果文件在构造函数中不存在,则抛出异常,并在 main() 中创建对象时尝试/捕获它,如果好 - 开始使用该对象
- 在类中声明并在 Main 中创建对象时隐式调用析构函数
- 如何在main之外的函数中创建对象