search

Home  >  Q&A  >  body text

c++隐式的类类型转换问题

这是书中的一道题目,为什么就combine2不能转换,而combine1和3就没问题?

#include <string>
using namespace std;
class Sales_data {
public:
    Sales_data() = default;
    Sales_data(const string& str) :data(str) {}

    Sales_data &combine1(Sales_data a) {}
    Sales_data &combine2(Sales_data& a) {}
    Sales_data &combine3(const Sales_data& a)const {}
private:
    string data;
};
int main() 
{
    string str = "hello";
    Sales_data item("9-999-99999-9");
    item.combine1(str);
    item.combine2(str);//error:无法将参数 1 从“std::string”转换为“Sales_data &”
    item.combine3(str);
}

巴扎黑巴扎黑2803 days ago497

reply all(2)I'll reply

  • ringa_lee

    ringa_lee2017-04-17 12:10:43

    The temporary object generated during implicit conversion is an rvalue, while the
    reference can only be bound to an lvalue, and the const reference can also be bound to an rvalue

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 12:10:43

    Want to take another look at "Quickly Understand Lvalues ​​and Rvalues ​​in C/C++"
    http://segmentfault.com/a/1190000003793498

    reply
    0
  • Cancelreply