c++ 在+运算符中使用右值引用

ltskdhd1  于 2024-01-09  发布在  其他
关注(0)|答案(1)|浏览(151)

我读了this,然后试着写了一个类(一个虚拟字符串类),在那里我可以试着看到右值引用的好处,就像那个文档中解释的那样。
但是我没有看到我的+(&&)运算符被调用。理论上&& based +运算符应该被调用来捕获对str2 +“test”+ str2表达式的(str2 +“test”)部分的右值引用。
代码如下:

  1. class Test
  2. {
  3. public:
  4. Test()
  5. {
  6. cout << "\nctor called";
  7. }
  8. Test(Test& obj)
  9. {
  10. cout << "\ncopy ctor called";
  11. }
  12. Test(Test&& rvalue_exp)
  13. {
  14. cout << "\nrvalue exp called";
  15. }
  16. Test operator+(const char* str)
  17. {
  18. cout << "\noperator + called " << str;
  19. }
  20. Test operator+(const Test& str)
  21. {
  22. cout << "\noperator +& called";
  23. }
  24. Test operator+(Test&& str)
  25. {
  26. cout << "\noperator +&& called";
  27. }
  28. void operator=(const Test& str)
  29. {
  30. cout << "\noperator + called";
  31. }
  32. };
  33. int main()
  34. {
  35. cout<<"Hello World";
  36. Test str, str2;
  37. str = str2 + "test" + str2;
  38. return 0;
  39. }
  40. output:
  41. Hello World
  42. ctor called
  43. ctor called
  44. operator + called test
  45. operator +& called
  46. operator + called

字符串
所以我的问题是,根据我链接的文档中的理论,用户如何从我的+运算符中受益?

evrscar2

evrscar21#

你混淆了

  1. Test operator+(Test&& str)

字符串

  1. Test& operator+(const Test& str) &&


str = str2 + "test" + str2;在右边没有右值,operator+的参数。
要呼叫您的操作员,请尝试以下操作:

  1. str = str1 + (str2 + "test");


还要注意,你的操作符返回了一个无效的类型,它应该返回一个引用。
你的操作符承诺返回值,但实际上并不返回任何东西。这导致了未定义的行为。

展开查看全部

相关问题