C++ - 二维数组作为方法参数

标签 c++

我有类似这样的类(class):

class Krzyzowka
{
    protected:
    char model[40][40];
    int x, y;

    public:
        Krzyzowka() { }

            Krzyzowka(char model[][40], int x, int y)
            {
                this->model=model;
            }
};

现在,我在 main() 中声明:

char array[10][10];

并想将其传递给:

Krzyzowka(char model[][40], int x, int y)

我是这样做的:

Krzyzowka obj(array, 10, 10);

但是我想用传递的数组设置模型二维数组:

this->model=model;

但是编译器返回两个错误:

error: no matching function for call to ‘Krzyzowka::Krzyzowka(char [10][10], int, int)’

error: incompatible types in assignment of ‘char (*)[40]’ to ‘char [40][40]’

我怎样才能正确地做到这一点?在此先感谢您的帮助。

最佳答案

参数 char model[][40] 只能用于数组,如 parameter[x][40]

如果你真的想将任何行数组传递给该方法,你可以使用指针:

class Krzyzowka
{
    protected:
        char **pp_model;
        int x, y;

    public:
        Krzyzowka() { }

        Krzyzowka(char **pp_model, int x, int y)
        {
            this->pp_model = pp_model;

            // do not miss follow two line
            this->x = x;
            this->y = y;
        }
};

然后,您可以传递 char ** 参数来实例化对象,而不是使用 char array[x][y]

现在您使用 c++。你最好不要使用行数组。那是 evil .您可以改用 STL vector 。

希望对您有所帮助:)

关于C++ - 二维数组作为方法参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10547227/

相关文章:

c++ - 如何从 C++ 中的 vector 中删除几乎重复项

c++ - Thrift C++ Trouble compiling provided 教程 - 无法在 TProcessor 上实例化抽象类

c++ - 我可以空基优化可变数据吗?

c++ - asio 分配示例中的 ‘typename’ 是什么意思

c++ - "Undefined Behavior"真的允许*任何*发生吗?

c++ - 通过修改的exp最快的pow()替换。当已经计算出较低的幂时,通过平方

C++ Durand-Kerner 根查找算法与 GMP 崩溃,但与 long double 不崩溃

c++ - Windows CE 上的主板蜂鸣声

c++ - C/C++ : Write and Read Sockets

c++ - constexpr 用户定义文字 : Is it allowed?