【问题标题】:Accessing main class instance methods from another class instantiated within the main class从主类中实例化的另一个类访问主类实例方法
【发布时间】:2016-01-15 08:44:33
【问题描述】:

我有两个类:“游戏”类和“单元”类。

游戏在程序启动后立即在 Main 函数中实例化。 在 Game 类构造函数中,我创建了一些“Unit”类实例。

然后我希望我的一个单元从我在 Main 函数中创建的 Game 类实例运行一个方法(例如使用 Game 的内置随机数引擎)

这可能吗?从这个类中实例化的类访问父类的实例方法的最佳方法是什么。

由于我真的不知道如何正确地做到这一点,我决定使用“静态”方法,尽管我的第一个需求是使用类的实例。仍然无法让它工作.. 这是我从我的 Game 类中使用 random 的尝试(但不是我想要的那个类的实例),我只能运行一个静态打印函数,但静态随机只会抛出一个错误:LNK2001 unresolved external symbol "public: static类 std::random_device Game::rgen" (?rgen@Game@@2Vrandom_device@std@@A)

顺便说一句,mt19937 给出了类似的错误。使用 Visual Studio 2015。

#include <iostream>
#include <random>

class Game;
class Unit;

class Game
{
public:
    Game();
    static void printSomething(); // test function

    static std::random_device rgen; // main game random generator

    // a shorthand function for quick generating random numbers 
    static int rnd(int min, int max){
        std::uniform_int_distribution<int> uid(min, max);
        return uid(rgen);
    }
    static double rnd(double min, double max){
        std::uniform_real_distribution<double> urd(min, max);
        return urd(rgen);
    }
};

class Unit
{
public:
    Unit() {
        std::cout << "unit created\n";
        Game::printSomething(); // this works
        std::cout << "random num is " << Game::rnd(1,100) << "!\n"; // this doesn't work
    }
};

// ********************************************** //
int main()
{
    Game game; // main game instance
}

// ********************************************** //

Game::Game() {
    Unit * unit = new Unit;
}

void Game:: printSomething() {
    std::cout << "Printing something!\n";
}

【问题讨论】:

  • 这似乎是一个非常主观的问题。我的选择是选择不同的类设计,将随机函数封装在您传递给UnitRandom 对象中。
  • 为什么不把生成器传过来,好像它应该有自己的类

标签: c++ class methods


【解决方案1】:

你得到那个错误,因为

static std::random_device rgen;

没有在类外声明。

您应该在类定义之后添加以下行:

std::random_device Game::rgen (*any constructor arguments needed*);

print 起作用的原因是,它没有使用未声明的静态变量 rgen。

【讨论】:

  • 谢谢,但它仍然没有回答主要问题,从主类中实例化的另一个类访问主类实例方法的方法是什么?
  • @Shabrido 为此,你应该做一些谷歌研究:stackoverflow.com/questions/11405069/…
  • 嘿..感谢这个链接,这几乎就是我想要的,相信我,我做了一些研究,但可能使用了错误的关键字。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-09
  • 2012-12-18
  • 2014-11-05
  • 1970-01-01
  • 2020-03-19
相关资源
最近更新 更多