我有这个结构:
struct NetDescriptor {
unsigned int inputNeuronCount = 1;
char **inputNeuronType = nullptr;
unsigned int hiddenNeuronCount = 0;
unsigned int *hiddenNeurons = nullptr;
unsigned int outputNeuronCount = 1;
char **outputNeuronType = nullptr;
};
并希望使用以下代码在其他类的方法中对其进行初始化:
NetDescriptor nnDescriptor = {
3,
{"EAT\n","FOODL\n","FOODR\n"},
3,
{4,4,3},
3,
{"EAT\n","MOVEL\n","MOVER\n"}
};
但这只会给我这个错误:
第3行:错误:类型为'char **'的标量初始值设定项大括号
我尝试过:
{{"EAT\n"},{"FOODL\n"},{"FOODR\n"}},
但是它没有任何改变,我也用std :: string尝试了同样的结果。
答案 0 :(得分:0)
我只想要一个包含字符串数组的结构 std :: string或char *,我想用STRUCT = { {“ 1”,“ 2”,“ 3”}};或类似的东西。
喜欢吗?
#include <iostream>
#include <string>
#include <vector>
struct NetDescriptor
{
char const *inputNeuronType[3];
};
struct NetDescriptorStr
{
std::string inputNeuronType[3];
};
struct NetDescriptorDynamic
{
std::vector<std::string> inputNeuronType;
};
int main()
{
NetDescriptor nnDescriptor = { { "EAT\n","FOODL\n","FOODR\n" } };
std::cout << nnDescriptor.inputNeuronType[1] << std::endl;
NetDescriptorStr nnDescriptorStr = { { "EAT\n","FOODL\n","FOODR\n" } };
std::cout << nnDescriptorStr.inputNeuronType[1] << std::endl;
NetDescriptorDynamic nnDescriptorDynamic = { { "EAT\n","FOODL\n","FOODR\n","EAT\n","FOODL\n","FOODR\n" } };
std::cout << nnDescriptorDynamic.inputNeuronType[4] << std::endl;
NetDescriptorDynamic nnDescriptorDynamic2;
nnDescriptorDynamic2.inputNeuronType.assign({ "EAT\n","FOODL\n","FOODR\n","EAT\n","FOODL\n","FOODR\n" });
std::cout << nnDescriptorDynamic2.inputNeuronType[4] << std::endl;
}
答案 1 :(得分:0)
问题本身与结构无关。
char **inputNeuronType = {"foo", "bar", "baz"};
有同样的问题。
指针是单个值。您不能使用表达式列表对其进行初始化。您只能将其指向某个已经存在的数组。
但是,如果您真正需要的只是初始化语法,那么std::vector<std::string>
就可以了:
#include <string>
#include <vector>
struct NetDescriptor {
unsigned int inputNeuronCount = 1;
std::vector<std::string> inputNeuronType;
unsigned int hiddenNeuronCount = 0;
std::vector<unsigned int> hiddenNeurons;
unsigned int outputNeuronCount = 1;
std::vector<std::string> outputNeuronType;
};
NetDescriptor nnDescriptor = {
3,
{"EAT\n","FOODL\n","FOODR\n"},
3,
{4,4,3},
3,
{"EAT\n","MOVEL\n","MOVER\n"}
};
此代码Just Works™。