C++ 无法将字符(*)[10]转换为字符**
可能重复:C++ 无法将字符(*)[10]转换为字符**,c++,C++,可能重复: 我试图为2D数组提供一个简单的getter函数,但我似乎无法找到发送它的正确语法 目前,我有以下几点: class Sample { public: char **get2D(); private: static const int x = 8; static const int y = 10; char two_d[x][y]; }; char** Sample::get2D() { return two_d; }; cla
我试图为2D数组提供一个简单的getter函数,但我似乎无法找到发送它的正确语法 目前,我有以下几点:
class Sample
{
public:
char **get2D();
private:
static const int x = 8;
static const int y = 10;
char two_d[x][y];
};
char** Sample::get2D()
{
return two_d;
};
class Sample
{
public:
static const int x = 8;
static const int y = 10;
typedef char Row[y];
Row *get2D();
private:
char two_d[x][y];
};
数组数组不同于指向数组的指针数组。在您的情况下,如果未在公共界面中发布数组宽度(
y
),则无法返回正确的类型。否则,编译器不知道返回数组的每一行有多宽
您可以尝试以下方法:
class Sample
{
public:
char **get2D();
private:
static const int x = 8;
static const int y = 10;
char two_d[x][y];
};
char** Sample::get2D()
{
return two_d;
};
class Sample
{
public:
static const int x = 8;
static const int y = 10;
typedef char Row[y];
Row *get2D();
private:
char two_d[x][y];
};
最好是这样做:
const char& operator()(int x1, int y1)
{
// Better to throw an out-of-bounds exception, but this is illustrative.
assert (x1 < x);
assert (y1 < y);
return two_d[x][y];
};
const char&operator()(int-x1,int-y1)
{
//最好抛出一个越界异常,但这是说明性的。
断言(x1
这使您能够安全地以只读方式访问阵列内部(可检查!)。更好的做法是只使用Boost Matrix库+1,虽然我不同意抛出异常更好。你应该两者都做。断言,然后是异常。异常很难追溯到抛出点。断言通常会触发一些实现定义的断点,以便与调试器一起进入。