2

编译此代码时,"Error: initialization with '{...}' expected for aggregate object"在我的函数调用中出现错误。我正在使用 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);
 }
4

2 回答 2

2

您正在返回临时参考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);
于 2012-12-03T23:34:01.177 回答
0

永远不要使用原生数组,它们非常糟糕,这是它们糟糕的方式之一。基本上,这将要求数组正常运行,而它们不会。语言强制的糟糕基本上意味着它们无法完成您对任何其他数据类型所期望的大量事情,而且当您可以std::array正常人一样使用它们时,它们真的不值得花时间使用。

使用std::array并感激甚至委员会接受 C 数组的吸吮。

有趣的是,我注意到您确实包含<array>,但后来没有使用std::array.

于 2012-12-03T23:11:24.003 回答