如何初始化constchar**数组

how to initialize const char** array

本文关键字:数组 constchar 初始化      更新时间:2023-10-16

这是我的代码

这是头文件。

class ShaderManager {
private:
const GLchar** vertexShaderCode_color;
const GLchar** fragmentShaderCode_color;
const GLchar** vertexShaderCode_texture;
const GLchar** fragmentShaderCode_texture;
ShaderManager();
~ShaderManager();

cpp文件。在构造函数中

vertexShaderCode_color = {
    "uniform mat4 uMVPMatrix;n"
    "attribute vec4 vPosition;n"
    "void main() { n"
    "   gl_Position = uMVPMatrix * vPosition; n"
    "}n"
};
fragmentShaderCode_color = {
    "precision mediump float;n"
    " uniform vec4 vColor;n"
    "void main() {n"
    "gl_FragColor = vColor;n"
    "}n"
};
vertexShaderCode_texture = {
    "uniform mat4 uMVPMatrix;n"
    "attribute vec4 vPosition;n"
    "attribute vec2 texCoord;n"
    " varying vec2 texCoordOut;n"
    "void main() {n"
    "gl_Position = uMVPMatrix * vPosition;n"
    "texCoordOut = texCoord;n"
    "}n"
};
fragmentShaderCode_texture = {
    "precision mediump float;n"
    "varying vec2 texCoordOut;n"
    "uniform sampler2D u_texture;n"
    "uniform vec4 vColor;n"
    " void main() {n"
    "  vec4 texColor = texture2D(u_texture, texCoordOut);n"
    "  gl_FragColor = texColor;n"
    "}n"
};

它不起作用。错误消息为:

错误3错误:无法在赋值中将"转换为"const GLchar**{aka const char**}"D: \workspace\VS2013\Projects\bbEngine2\bbEngine2\src\GLManager\ShaderManager.cpp 10 2 bbEngine2

如何初始化constchar**数组

以与其他阵列相同的方式。

const GLchar** vertexShaderCode_color;

这不是const char**数组。它是指向const GLchar*的单个指针。

vertexShaderCode_color = {
    "uniform mat4 uMVPMatrix;n"
    "attribute vec4 vPosition;n"
    "void main() { n"
    "   gl_Position = uMVPMatrix * vPosition; n"
    "}n"
};

这就是初始化数组的方法。但正如我已经指出的,您并没有将vertexShaderCode_color声明为数组。这是一个指针。此外,如果它在构造函数体内部,则该成员已经初始化。不能分配给数组。

如果您确实希望vertexShaderCode_color是一个数组,那么您需要将其声明为一个数组。请记住,数组的大小必须在运行时已知:

const char* vertexShaderCode_color[5];

然后在成员初始化器列表或默认成员初始化器中初始化它。

我想你需要这样的东西:

static const char* vertexShaderCode_color_value[] = {
    "uniform mat4 uMVPMatrix;n"
    "attribute vec4 vPosition;n"
    "void main() { n"
    "   gl_Position = uMVPMatrix * vPosition; n"
    "}n"
};
vertexShaderCode_colour = vertexShadeCode_colour_value;

您正被C和C++中数组和指针之间的细微差异所打动。

编辑:我以为你需要对变量进行名称空间限定,但我看到这是在构造函数中。。。在这种情况下,如果不能使用静态变量作为值,则需要进行一些内存分配:

类内定义:

std::vector<const GLChar*> vertexShaderCode_color_value;
GLChar** vertexShaderCode_color;  // Order is significant.

在初始值设定项列表中:

    vertexShaderCode_colour_value { ... },
    vertexShaderCode_colour { &vertexShaderCode_colour_value.front() },

(如果您愿意,也可以在构造函数主体中执行)