0

-------------------问题1:------------

我有一个场景类,我想制作一系列场景,称为......嗯......“场景”:

class Scene
{
public:
    int id;
    string title;
    Image backgroundImage;
    Scene( int id, string title, Image backgroundImage );
};

我在游戏头中的 Game 类中声明了场景数组:

Scene scenes[ 2 ];

然后我开始用我的game.cpp循环de循环中的场景来抽它:

scenes[ 0 ] = Scene();

为什么我可以在不必声明新场景的情况下完成上述操作?例如:

scenes[ 0 ] = new Scene();

是因为我没有将类 Scene 声明为 public 吗?它是作为静态的还是其他东西创建的?我很困惑史酷比!

- - - - - - - - - - 问题2 - - - - - - - - - - - -

有没有更好的方法将场景的属性传递给构造函数......例如在javascript中你可以这样做:

var Scene = function( properties )
{
    this.id = properties.id;
    this.string = properties.string;
    this.backgroundImage = properties.backgroundImage;
}

var scenes = [
    new Scene( { 
        id:0, 
        string:"a scene", 
        Image: new Image( ... ) 
    } ),        
    new Scene( { 
        id:1, 
        string:"a scene 1", 
        Image: new Image( ... ) 
    } ),
]

然后这成为自我记录.. d'ya 抓到我的漂流布拉?

- - - - - - 笔记 - - - - - - :

我认为您必须将其声明为新的,因为我不知道仅说场景[0] = Scene() 声明了对象的新实例?

4

5 回答 5

1
Scene scenes[2];

Scene这将创建一个包含 2 个对象的数组。不是指向对象的指针。对象。每个对象都使用默认构造函数进行初始化。

要创建一个包含由其他构造函数初始化的对象的数组,只需执行以下操作:

Scene scenes[2] = {
  Scene(0, "a scene", Image(...)),
  Scene(1, "a scene 1, Image(...)) };
于 2013-03-27T22:11:28.947 回答
1
#include <string>
using namespace std;

struct Image {};

class Scene
{
private:
    int id_;
    string title_;
    Image backgroundImage_;
public:
    Scene( int id, string const& title, Image const& backgroundImage )
        : id_( id )
        , title_( title )
        , backgroundImage_( backgroundImage )
    {}
};

#include <iostream>
int main()
{
    Scene scenes[] = {
        Scene( 0, "a scene", Image()  ),
        Scene( 1, "a scene 1", Image()  )
        };
    // Whatever.
}
于 2013-03-27T22:14:18.933 回答
1
  1. 在 JavaScript 中,new创建一个对象,而在 C++ 中,它返回一个指向该新创建对象的指针。这样做scenes[0] = Scenes()是正确的。

  2. 也许你可以试试std::vector

    #include <vector>
    
    std::vector<Scenes> scenes{
        Scenes{0, "a scene", Image{}},
        Scenes{1, "a scene1", Image{}},
    };
    
于 2013-03-27T22:15:23.610 回答
0

你要这个:

class Scene
{
    int id;
    string title;
    Image backgroundImage;

public:
    Scene(int id, string const & title, Image const & backgroundImage)
    : id(id)
    , title(title)
    , backgroundImage(backgroundImage)
    { }
};

Scene scenes[2] = { Scene(1, "me", image1), Scene(2, "you", image2) };

使用现代编译器 (C++11),您还可以编写:

Scene scenes[2] = { {1, "me", image1}, {2, "you", image2} };

你可能更喜欢std::array<Scene, 2>.

于 2013-03-27T22:10:16.767 回答
0

对于你的第一个问题:

Scene scenes[ 2 ]; /declares an array of Scene objects
scenes[ 0 ] = Scene();
How comes I can do the above without having to declare a new Scene? for example:

scenes[ 0 ] = new Scene();
Is it because I did not declare the class Scene as public? 

new运算符创建一个对象,返回一个pointer类的对象。如果使用new,则需要将数组声明为指向 的指针数组Scene。在您的对象数组情况下,如果您不指定调用哪个构造函数来初始化这些对象,它将调用默认构造函数。

于 2013-03-27T22:11:42.993 回答