#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); // ⚠️ 僅示範,實際極度危險 } }
同理,分別用 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);。去空格預處理可加健壯性。
io_service 為核心,同步 API 易上手,異步才是高性能關鍵。