c++ 逗号操作符重载

比眉伴天荒 2022-07-26 00:21 279阅读 0赞

Overload Operator Comma

首先看看think in c++ 给出的一个重载的例子

  1. #include <iostream>
  2. using namespace std;
  3. class After {
  4. public:
  5. const After& operator,(const After&) const {
  6. cout << "After::operator,()" << endl;
  7. return *this;
  8. }
  9. };
  10. class Before {};
  11. Before& operator,(int, Before& b) {
  12. cout << "Before::operator,()" << endl;
  13. return b;
  14. }
  15. int main() {
  16. After a, b;
  17. a, b; // Operator comma called
  18. Before c;
  19. 1, c; // Operator comma called
  20. } ///:~

下面是实际使用中用到的例子

  1. #include <iostream>
  2. #include <typeinfo>
  3. using namespace std;
  4. class CClient
  5. {
  6. public:
  7. CClient(){};
  8. ~CClient(){};
  9. public:
  10. CClient& operator,(string str)
  11. {
  12. strIpAddr_=str;
  13. return *this;
  14. }
  15. CClient& operator,(int nVal)
  16. {
  17. nPort_=nVal;
  18. return *this;
  19. };
  20. bool connect()
  21. {
  22. //Connect(strIpAddr_,nPort_);
  23. cout<<"connect to server "<<endl;
  24. return true;
  25. }
  26. public:
  27. string strIpAddr_;
  28. int nPort_;
  29. };
  30. struct OutputDebugInfo
  31. {
  32. OutputDebugInfo& operator,(string str)
  33. {
  34. cout<<str;
  35. }
  36. };
  37. #define outputDebugInfo OutputDebugInfo{},
  38. int main() {
  39. (CClient {},80,"192.168.1.10").connect();
  40. outputDebugInfo "Log: this is Debug Infomation Test \n";
  41. return 0;
  42. }

输出信息

Center

发表评论

表情:
评论列表 (有 0 条评论,279人围观)

还没有评论,来说两句吧...

相关阅读

    相关 C++操作符重载

    又看了一遍操作符的东西,感觉之前对操作符的理解还停留在很浅的认知上(仅仅会用哈哈),所以做一下笔记来加深一下印象。 文章目录 一、为什么会有操作符重载

    相关 C++中操作符重载

    一、操作符重载属于什么? 在本文开始阐述之前,首先明确,操作符重载是一个具有特殊名的“ 函数 ”。 既然作为函数,那么,就具有函数的特性,一是形参表,二是返回值。 关键字