考虑下面的代码:
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]$
原文链接: https://www.cnblogs.com/StupidTortoise/p/3663151.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/127459
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!