Vote count:
0
I have questions about the return type of function in C++.
Why return pair<int, int>(1, 1);
and return vector<int>(3, 3);
work? Shouldn't I create an local instance var before hand and take it as the return value, just like the return a, because return int 1 doesn't work.
// ...
int fun1() {
// return int 1;
int a = 1;
return a;
}
pair<int, int> fun2() {
return pair<int, int>(1, 1);
}
vector<int> fun3() {
return vector<int>(3, 3);
}
int main(){
cout << fun1() << endl;
cout << fun2().first << endl;
cout << fun3()[1] << endl;
return 0;
}
Is it such a style to return can only be applied on class instances with specific constructor? The example below can work. I'm looking for confirmation, thanks at advance!
class A {
public:
int a;
A(int a_) : a(a_) {};
};
A fun4() {
return A(1);
}
Code sample tested in:
Apple LLVM version 6.0 (clang-600.0.56) (based on LLVM 3.5svn) Target: x86_64-apple-darwin14.0.0 Thread model: posix
asked 45 secs ago
Return an anonymous instance/value in functions in C++
Aucun commentaire:
Enregistrer un commentaire