C++主函数传递对象实现双向收发消息功能异常问题求助
C++双向消息收发问题修复说明
你不需要在sendMsg中创建对象副本,当前传递引用的写法本身是正确的,无法正常显示双向消息是代码逻辑和细节错误导致的,具体问题和修复方案如下:
核心错误点
- 遍历方法的循环条件错误:
Message::showMsg和Inbox::showRecievedMsg两个方法的for循环终止条件写反了,你用了容器的begin和end比较,而不是迭代器it和end比较,会导致无限循环。 - 打印调用逻辑错误:你调用
user2.sendMsg(user1, "Hi")时,这条消息会存入user2的发件箱、user1的收件箱,原代码中调用user2.showRecievedMsg()自然看不到对应内容,应该调用user2.showSendMsg()看user2发出的消息,调用user1.showRecievedMsg()看user1收到的消息。
修复后完整代码
#include<bits/stdc++.h> using namespace std; class Message{ private: list<string> msg; public: void setMsg(string s){ this->msg.push_front(s); } list<string> getMsg(){ return this->msg; } void showMsg(){ // 修复循环条件 for (auto it = this->msg.begin(); it != this->msg.end(); it++) cout << *it << endl; } }; class Inbox{ private: Message m; list<string> r_msg; public: void sendMsg(Inbox &i, string s){ this->m.setMsg(s); i.r_msg.push_front(s); } void showSendMsg(){ m.showMsg(); } void showRecievedMsg(){ // 修复循环条件 for (auto it = this->r_msg.begin(); it != this->r_msg.end(); it++) cout << *it << endl; } }; int main(){ Inbox user1, user2; user1.sendMsg(user2, "hello"); cout << "===== user1发件箱 =====" << endl; user1.showSendMsg(); cout << "===== user2收件箱 =====" << endl; user2.showRecievedMsg(); user2.sendMsg(user1, "Hi"); cout << "\n===== user2发件箱 =====" << endl; user2.showSendMsg(); cout << "===== user1收件箱 =====" << endl; user1.showRecievedMsg(); user1.sendMsg(user2, "What are you doing?"); cout << "\n===== user1发件箱 =====" << endl; user1.showSendMsg(); cout << "===== user2收件箱 =====" << endl; user2.showRecievedMsg(); user2.sendMsg(user1, "Nothing!!"); cout << "\n===== user2发件箱 =====" << endl; user2.showSendMsg(); cout << "===== user1收件箱 =====" << endl; user1.showRecievedMsg(); user1.sendMsg(user2, "Are you there?"); cout << "\n===== user1发件箱 =====" << endl; user1.showSendMsg(); cout << "===== user2收件箱 =====" << endl; user2.showRecievedMsg(); user2.sendMsg(user1, "I am lil bit buzy"); cout << "\n===== user2发件箱 =====" << endl; user2.showSendMsg(); cout << "===== user1收件箱 =====" << endl; user1.showRecievedMsg(); return 0; }
内容的提问来源于stack exchange,提问作者user9387385
相关产品推荐
相关产品推荐

