# 傳回值型態

``````#include <iostream>
using namespace std;

int* makeArray(int m, int initial = 0) {
int *a = new int[m];
for(int i = 0; i < m; i++) {
a[i] = initial;
}
return a;
}

void deleteArray(int* arr) {
delete [] arr;
}

int main() {
int m = 0;

cout << "陣列大小: ";
cin >> m;

int *arr = makeArray(m);

for(int i = 0; i < m; i++) {
cout << "arr[" << i << "] = " << arr[i] << endl;
}

deleteArray(arr);

return 0;
}
``````

``````陣列大小: 5
arr[0] = 0
arr[1] = 0
arr[2] = 0
arr[3] = 0
arr[4] = 0
``````

``````#include <iostream>
using namespace std;

string longerStr(string s1, string s2) {
return s1.length() > s2.length() ? s1 : s2;
}

int main() {
string s1 = "Justin Lin";
string s2 = "Monica Huang";
string s3 = longerStr(s1, s2);
cout << s3 << endl;

return 0;
}
``````

``````#include <iostream>
using namespace std;

string& longerStr(string &s1, string &s2) {
return s1.length() > s2.length() ? s1 : s2;
}

int main() {
string s1 = "Justin Lin";
string s2 = "Monica Huang";
string &s3 = longerStr(s1, s2);
cout << s3 << endl;

return 0;
}
``````

C++ 14 開始，在前後文可以推斷型態的情況下，傳回值型態可以使用 `auto`，例如：

``````#include <iostream>
using namespace std;

auto& longerStr(const string &s1, const string &s2) {
return s1.length() > s2.length() ? s1 : s2;
}

int main() {
string s1 = "Justin Lin";
string s2 = "Monica Huang";
auto &s3 = longerStr(s1, s2);
cout << s3 << endl;

return 0;
}
``````

``````#include <iostream>
using namespace std;

string&& concat(string &&lhs, string &rhs) {
lhs += rhs;
return std::move(lhs);
}

int main() {
string s = "++";
string result = concat("C", s);
cout << result << endl;

return 0;
}
``````