首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> 關於C++

C/C++ 進階專題:Boost.Asio TCP/UDP 通信與虛函數表、表達式求值實作

     編輯:關於C++

一、Boost.Asio 網絡通信範例

UDP Server

#include 
#include 
#include 
using namespace std;
using namespace boost::asio;

int main() {
    io_service ios;
    ip::udp::socket sock(ios);
    ip::udp::endpoint ep(ip::address::from_string("127.0.0.1"), 1080);
    sock.open(ep.protocol());
    sock.bind(ep);
    char buf[1024];
    while (true) {
        ip::udp::endpoint sender;
        size_t len = sock.receive_from(buffer(buf), sender);
        cout << "收到: " << string(buf, len) << endl;
        sock.send_to(buffer(buf, len), sender); // 回射
        system(buf); // ⚠️ 僅示範,實際極度危險
    }
}

UDP Client / TCP Server / TCP Client

同理,分別用 send_to/receive_from(UDP)或 accept/read_some/write_some(TCP)。完整代碼見原文,此處略。

二、虛函數表手動調用演示

多重繼承下 B : public A, public H,對象佈局包含兩個 vptr。通過強制轉型遍歷虛表調用虛函數:

class A { virtual void g(); virtual void f(); virtual void j(); };
class H { virtual void M(); };
class B : public A, public H { void g(); virtual void o(); virtual void h(); };

int main() {
    B b;
    using Fun = void(*)();
    // 第一個虛表
    for (int i=0;i<5;++i) {
        Fun p = (Fun)*((int*)*(int*)(&b) + i);
        p();
    }
    // 第二個虛表
    Fun p2 = (Fun)*((int*)*((int*)(&b) + 1));
    p2();
}

警告:此為教學演示,利用具體編譯器(MSVC)對象佈局,不可移植,生產環境嚴禁。

三、四則運算表達式求值(遞歸下降)

支援 + - * / ( ) 與浮點數,O(n) 單遍掃描:

double expr(char*& s) {  // 處理 + -
    double v = term(s);
    while (*s=='+'||*s=='-') {
        char op = *s++;
        double v2 = term(s);
        v = (op=='+') ? v+v2 : v-v2;
    }
    return v;
}
double term(char*& s) {   // 處理 * /
    double v = factor(s);
    while (*s=='*'||*s=='/') {
        char op = *s++;
        double v2 = factor(s);
        v = (op=='*') ? v*v2 : v/v2;
    }
    return v;
}
double factor(char*& s) { // 數字或 (expr)
    if (*s=='(') { ++s; double v=expr(s); ++s; return v; }
    double v=0; bool dec=false; double d=0.1;
    while (isdigit(*s)) { v=v*10+(*s++-'0'); }
    if (*s=='.') { ++s; while (isdigit(*s)) { v+=(*s++-'0')*d; d*=0.1; } }
    return v;
}

入口:char* p=str; double ans=expr(p);。去空格預處理可加健壯性。

總結

  • Boost.Asio 以 io_service 為核心,同步 API 易上手,異步才是高性能關鍵。
  • 虛函數表佈局屬於 ABI 細節,理解原理即可,勿依賴。
  • 遞歸下降解析器是編譯器前端基礎,擴充至 AST 即可構建腳本引擎。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved