3

私はc ++を学んでいて、いくつかのことを試しています。コンパイラは、コメント 2 行でエラーをスローしていません。

int main(){
   vector<double> a1;
   a1.push_back(3);
   a1.push_back(7);
   a1.push_back(2);
   vector<double>& a2 = a1;          //COMMENT 1: This line has no error
   vector<double>& a4 = print(a2);   //COMMENT 2: Why this line has error? R value is an object then it should be referenced by a4? 
   return 0;
}

vector<double> print(vector<double>& a3){
   cout<<"In print function the size of vector is :";
   cout<<a3.size()<<endl;
   return a3;
}
4

2 に答える 2

3

の戻り値の型はprint参照ではないため、 のコピーを返しますa3。これは一時的なものであり、参照にバインドすることはできません。

これは次の方法で修正できます。

vector<double>& print(vector<double>& a3){
//            ^
// note the ampersand here
于 2013-07-28T05:00:00.133 に答える