WHCSRL 技术网

c++成员运算符的重载

 

下面是自己编写的一个例子 

  1. #include <string>
  2. #include <iostream>
  3. #include <memory>
  4. using namespace std;
  5. class B
  6. {
  7. public:
  8. B() = default;
  9. B(const string &str):arr({"sss1","sss2","sss3","sss4"}),curr(0){}
  10. string & operator*()
  11. {
  12. return arr[curr];
  13. }
  14. string * operator->()
  15. {
  16. return & this->operator*();
  17. }
  18. private:
  19. size_t curr = 0;
  20. string arr[100] = {"str1","str2","str3","str4"};
  21. };
  22. class A
  23. {
  24. public:
  25. A() = default;
  26. A(const string & str)
  27. {
  28. for(int i = 0;i != 100; ++i)
  29. {
  30. bind[i] = B("ok");
  31. }
  32. }
  33. B& operator*()
  34. {
  35. return bind[curr];
  36. }
  37. B& operator->()
  38. {
  39. return operator*();//这里因为operator*返回对象
  40. }
  41. private:
  42. size_t curr = 0;
  43. B bind[100];
  44. };
  45. int main()
  46. {
  47. A a;
  48. cout << a->size() << endl;
  49. return 0;
  50. }

推荐阅读