首页 > 解决方案 > 'char **':dynamic_cast 的目标类型无效

问题描述

我已经编写了以下代码,但是当我编译它时,编译器给了我一堆关于动态转换用法的错误。我应该如何解决这个问题?我必须使用 c++ 功能实现代码。

#include <iostream>
#include <ctime>

void draw(void* u, int w, int h) {
    char(*world)[w] = dynamic_cast<char**>(u);
    for (int y = 0; y < h; y++) {
        for (int x = 0; x < w; x++)
            std::cout << world[y][x] ? "*" : " ";
        std::cout << '\n';
    }
}

int main() {
    int w = 30;
    int h = 30;
    char world[h][w];
    for (int x = 0; x < w; x++)
        for (int y = 0; y < h; y++)
            world[y][x] = rand() < RAND_MAX / 10 ? 1 : 0;

    draw(world, w, h);
    return 0;
}

ٍ错误:

error C2131: expression did not evaluate to a constant
message : failure was caused by a read of a variable outside its lifetime
message : see usage of 'w'
error C2680: 'char **': invalid target type for dynamic_cast
message : target type must be a pointer or reference to a defined class
error C2131: expression did not evaluate to a constant
message : failure was caused by a read of a variable outside its lifetime
message : see usage of 'h'
error C2131: expression did not evaluate to a constant
message : failure was caused by a read of a variable outside its lifetime
message : see usage of 'w'
error C3863: array type 'char [h][w]' is not assignable
> Blockquote

标签: c++

解决方案


error C2131: expression did not evaluate to a constant

C 可以使用变量作为数组大小,但 C++ 不能。用于std::vector动态大小的数组、std::array静态大小的数组和 C 样式的数组从不使用。

error C2680: 'char **': invalid target type for dynamic_cast

dynamic_cast仅对多态类类型的指针和引用有效,并且不char**限定void *</sup>。只需传递正确的类型而不是,void *您根本不需要演员表。

†</sup> dynamic_casting to void*有一个例外,但在这里并不适用。

error C3863: array type 'char [h][w]' is not assignable

不言自明:不能复制或分配 C 样式的数组。切换到std::vector也可以解决这个问题。

应用了这些修复的代码:

#include <iostream>
#include <ctime>
#include <cstdlib>
#include <vector>

void draw(std::vector<std::vector<char>> const &world, int w, int h) {
    for (int y = 0; y < h; y++) {
        for (int x = 0; x < w; x++)
            // Also fixed the missing parentheses here
            std::cout << (world[y][x] ? "*" : " ");
        std::cout << '\n';
    }
}

int main() {
    int w = 30;
    int h = 30;
    std::vector<std::vector<char>> world(h, std::vector(w, '\0'));
    for (int x = 0; x < w; x++)
        for (int y = 0; y < h; y++)
            world[y][x] = rand() < RAND_MAX / 10 ? 1 : 0;

    draw(world, w, h);
    return 0;
}

在 Wandbox 上现场观看

进一步的改进:

  • using World = std::vector<std::vector<char>>避免重复
  • 如果连续行更可取,则将嵌套向量替换为矩阵类
  • 使用 C++<random>工具而不是 C 的rand()

推荐阅读