gpt4 book ai didi

C++, "Error: initialization with ' {... }' expected for aggregate object"

转载 作者:太空宇宙 更新时间:2023-11-04 12:02:09 32 4
gpt4 key购买 nike

编译这段代码时,我在调用函数时收到错误,“错误:聚合对象需要使用 '{...}' 进行初始化”。我正在使用 Visual Studio 11 进行编译。

#include <iostream>
#include <string>
#include <array>
using namespace std;

typedef std::array<string, 5> string_t;
string_t centerString(std::array<string, 5> (&tempArray),unsigned short int length);
string_t evenString(std::array<string, 5> (&tempArray),unsigned short int length);

int main(){
std::array<string, 5> aArray = {"a","aa","aaa","aaaa","aaaaa"};

std::array<string, 5> evenStr[5] = evenString(aArray,5);
std::array<string, 5> centerStr[5] = centerStr(aArray,5);
}


string_t evenString(std::array<string, 5> (&srcArray),unsigned short int length){
std::array<string, (sizeof(srcArray)/sizeof(srcArray[0]))> trgtArray= {};
for(unsigned short int x = 0; x < (sizeof(srcArray)/sizeof(srcArray[0]));x++){
trgtArray[x] = srcArray[x];
for(unsigned short int y = 0; y < (length-trgtArray[x].length()); y++){
trgtArray[x] += " ";
}
}

return(trgtArray);
}

string_t centerString(std::array<string, 5> (&srcArray),unsigned short int length){
std::array<string, (sizeof(srcArray)/sizeof(srcArray[0]))> trgtArray= {};
unsigned short int remainder;
string spacer = "";
for(unsigned short int x = 0; x < (sizeof(srcArray)/sizeof(srcArray[0]));x++){
remainder = length - srcArray[x].length();
if((remainder % 2) == 0){
trgtArray[x] = srcArray[x];
for(unsigned short int y = 0; y < (length-srcArray[x].length()); y++){
trgtArray[x] += " ";
}
}else{
for(unsigned short int z = 0; z < (remainder/2); z++){
spacer += " ";
}
trgtArray[x] = spacer + srcArray[x] + spacer + " ";
}
}

return(trgtArray);
}

最佳答案

您正在 centerString 中返回临时引用

string_t& centerString(std::array<string, 5> (&tempArray),unsigned short int length);

centerStr 是数组,不能作为函数使用

std::array<string, 5> centerStr = centerStr(aArray,5);

我想你的意思是

std::array<string, 5> centerStr = centerString(aArray,5);

您可以尝试下面的示例函数,只需返回数组,RVO 就会启动。

std::array<string,5> evenString(std::array<string, 5> (&srcArray), unsigned short length){
std::array<string,5> trgtArray = {};
//....
return trgtArray;
}

std::array<string, 5> evenStr = evenString(aArray,5);
std::array<string, 5> centerStr = centerString(aArray,5);

关于C++, "Error: initialization with ' {... }' expected for aggregate object",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13693331/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com