初始化在C的二维对象数组++ [英] Initializing a two-dimensional object array in c++
问题描述
我知道这之前已经被要求(或一些类似的变化),但是我不能得到它的工作。
I know this has been asked before (or some similar variations) however I cannot get it to work.
我想创建一个由充满正方形板的棋盘游戏。我想我的主板型号为广场对象的二维数组。该板可与任何宽度或高度被创建,这些参数是通过构造函数传递。这里是code我一起工作:
I am trying to create a board game that is composed of a board filled with squares. I am trying to model my board as a 2d array of Square objects. The board can be created with any width or height, and those parameters are passed in through the constructor. Here is the code I am working with:
Board.h
#ifndef BOARD_H
#define BOARD_H
#include "Square.h"
class Board{
public:
Board(int w, int h);
private:
Square **squares;
const int width;
const int height;
};
#endif
Board.cpp
#include "Board.h"
Board::Board(int w, int h):width(w), height(h) {
squares = new Square*[width];
for (int i = 0; i < width; i++) {
squares[i] = new Square[height];
}
}
然而,当我尝试编译此,我得到这似乎预示着平方错误[I] =新广场[高度]
试图调用默认的构造函数为方形对象(我不想存在也不在这种情况下,调用)。
However, when I try to compile this I get an error which seems to indicate the squares[i] = new Square[height]
is trying to call the default constructor for the Square object (which I do not want to exist nor call in this case).
Board.cpp: In constructor ‘Board::Board(int, int)’:
Board.cpp:7:33: error: no matching function for call to ‘Square::Square()’
squares[i] = new Square[height];
任何想法?这是可能的范围内C ++?
Any ideas? Is this possible within C++?
推荐答案
您code是相同的:
struct Foo
{
Foo(int){} // no default constructor
// Foo() = default; /* uncomment this and it will work */
};
int main()
{
Foo* pFoo = new Foo[10]; // need a default ctor
delete[] pFoo;
}
问题是,在美孚* PFOO =新富的RHS [10];
,你是分配内存的以及创建 10 富
的对象。编译器不知道该怎么办后者(创建对象),因为你不提供一个默认的构造函数。为了使上述code工作原样,则需要指定全部作为每个对象的非默认的构造函数,如参数:
The problem is that on the rhs of Foo* pFoo = new Foo[10];
, you are allocating the memory as well as creating 10 Foo
objects. The compiler doesn't know how to do the latter (creating the objects), as you don't provide a default constructor. To make the above code work as is, you need to specify all arguments for the non-default ctor of each object, like:
Foo* pFoo = new Foo[10]{1,2,3,4,5,6,7,8,9,0}; // this will work
更好的替代方法是使用 STD: :矢量
代替。如果你想知道为什么,无需后期作品没有一个默认的构造函数的对象,这是因为它使用的布局新
,并初始化需求的元素。
The better alternative is to use std::vector
instead. If you wonder why the latter works without the need for objects that don't have a default constructor, it is because it uses the placement new
, and initializes the elements on demand.
这里你可以看到如何使用位置新
。
Here you can see how to do it with placement new
.
修改
在code
Foo* pFoo = new Foo[10]{1,2,3,4,5,6,7,8,9,0};
在编译GCC,但铛无法编译它(与 -std = C ++ 11
标志)。这里跟进问题。
compiles in gcc, but clang fails to compile it (with -std=c++11
flag). Follow up question here.
这篇关于初始化在C的二维对象数组++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!