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]$ 

 

转载于:https://www.cnblogs.com/StupidTortoise/p/3663151.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值