C++随笔:引用类型与临时变量
考虑下面的代码:
1 #include <iostream> 2 #include <string> 3 using std::cout; 4 using std::endl; 5 using std::string; 6 7 class Test 8 { 9 public: 10 Test() 11 { 12 cout << "Test() is called!" << endl; 13 } 14 15 Test(string strTemp) 16 { 17 cout << "Test(string) is called!" << endl; 18 } 19 20 void testFun(Test &rhs) 21 { 22 cout << "testFun(Test &) is called!" << endl; 23 } 24 25 private: 26 int i; 27 }; 28 29 int main() 30 { 31 Test myTestA; 32 33 string strTest = "test"; 34 myTestA.testFun(strTest); 35 36 return 0; 37 }
第34行:
myTestA.testFun(strTest);
由于 testFun 的参数类型为:Test &,而刚好存在参数为 string 类型的构造函数,所以首先进行了 string 类型到 Test 类的隐式转换,生成一个临时变量,然后把这个临时变量作为参数传给 testFun 成员函数,但是引用类型不能绑定到一个临时变量上,所以编译器报错了:
[tortoise@sea temp]$ g++ -std=c++11 -o temp temp.cc temp.cc: In function ‘int main()’: temp.cc:34:25: error: no matching function for call to ‘Test::testFun(std::string&)’ myTestA.testFun(strTest); ^ temp.cc:34:25: note: candidate is: temp.cc:20:7: note: void Test::testFun(Test&) void testFun(Test &rhs) ^ temp.cc:20:7: note: no known conversion for argument 1 from ‘std::string {aka std::basic_string<char>}’ to ‘Test&’ [tortoise@sea temp]$
即使将 string 类型显式转换为 Test 类型,也同样报错:
myTestA.testFun(Test(strTest));
[tortoise@sea temp]$ g++ -std=c++11 -o temp temp.cc temp.cc: In function ‘int main()’: temp.cc:34:31: error: no matching function for call to ‘Test::testFun(Test)’ myTestA.testFun(Test(strTest)); ^ temp.cc:34:31: note: candidate is: temp.cc:20:7: note: void Test::testFun(Test&) void testFun(Test &rhs) ^ temp.cc:20:7: note: no known conversion for argument 1 from ‘Test’ to ‘Test&’ [tortoise@sea temp]$
临时变量只能由 const 引用类型绑定,所以需要将 testFun 成员函数的参数类型修改为:
void testFun(const Test &rhs) { cout << "testFun(const Test &) is called!" << endl; }
编译运行:
[tortoise@sea temp]$ g++ -std=c++11 -o temp temp.cc [tortoise@sea temp]$ ./temp Test() is called! Test(string) is called! testFun(const Test &) is called! [tortoise@sea temp]$
浙公网安备 33010602011771号