如何在成员函数中创建动态对象?

How to create dynamic objects in member function?

在 Class Championship 的成员函数中,我尝试创建动态对象并调用 Class Game 的成员函数,但我得到的错误消息是 error: expected primary-expression before '[' token。如何纠正?

class Championship
{
public:
    Championship(string,int);
    void CreateGame();
    void display();
 private:
    int gamenum;
};
class Game
{
public:
    friend class Championship;
    void Getteam();
};
void Championship::CreateGame()
{   
    Game *game = new Game[gamenum];
    for (int i = 0; i < gamenum; i++)
        Game[i].Getteam();
}

编辑:虽然这个答案没有直接解决问题,但它确实提供了一种有用的替代语法来分配用户定义对象的数组。

这可能可以使用经典的 C 风格双指针数组(即来自 int main(int argc, char** argv) 的 argv)不太优雅地解决。这样的代码将首先分配 space 为数组,然后使用带有索引的循环为每个单独的对象分配 space。

#include <iostream>

class Foo
{
public:
    //Constructor to ensure each object is unique with an int + loop
    Foo(int k)
    : i(k)
    {}

    int i;

    int operator() () {return i;}
};

int main ()
{ 
    //Arbitrary number for allocation; get this somehow
    int i = 5;

    //Although it can be unsafe, allocate an array of pointers with a pointer to pointer
    Foo** array = new Foo*[i];

    for (int j = 0; j < i; ++j)
    {
        array[j] = new Foo(j);
        //Here, I use operator() to test that each object is unique.
        std::cout << (*array[j])() << std::endl;
    }

    //Using Coliru, the program will work and print out this
    std::cout << "this worked!\n";
    return 0;
}

科里鲁:http://coliru.stacked-crooked.com/a/84f7641e5c4fa2f3

您在代码中面临的确切问题就在这一点上

Game *game = new Game[gamenum];
for (int i = 0; i < gamenum; i++)
    Game[i].Getteam();

这里的主要问题是您已经声明了一个类型为 Game 的数组并将其命名为 game 但随后您尝试使用类型 Game 进行访问,所以很简单将其换回 game 即可解决该问题。

但是,没有必要以这种方式使用原始指针。 std::vector 在很多方面都比这里优越。它允许您以安全的方式动态地将越来越多的对象添加到容器中。我正要展示如何在您的 Championship::CreateGame() 函数中使用 std::vector...但我无法真正弄清楚它正在尝试做什么...

我也不明白为什么你的游戏中有 friend 行 class... 用于让另一个 class 'full' 访问您的 class,即 Championship class 可以访问 Game.

的私有成员