c++ - 将对象传递给main中的函数的问题
问题描述
如何在主函数中传递对象。我想显示用户 1 向用户 2 和用户 2 向用户 1 发送和接收的消息,但是当我使用调用者对象调用函数时,它只显示用户 1 发送消息
请帮我解决这个问题。我不明白我在做什么,我可以在类中的sendMsg()
函数中制作传递引用对象的单独副本吗Inbox
#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(); this->msg.begin() != 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(); this->r_msg.begin() != this->r_msg.end(); it++)
cout << *it << endl;
}
};
int main(){
Inbox user1, user2;
user1.sendMsg(user2, "hello");
user1.showSendMsg();
user2.sendMsg(user1, "Hi");
user2.showRecievedMsg();
user1.sendMsg(user2, "What are you doing?");
user1.showSendMsg();
user2.sendMsg(user1, "Nothing!!");
user2.showRecievedMsg();
user1.sendMsg(user2, "Are you there?");
user1.showSendMsg();
user2.sendMsg(user1, "I am lil bit buzy");
user2.showRecievedMsg();
return 0;
}
解决方案
问题在于,在第 18 行中,您正在与this->msg.begin()
末尾进行比较,而不是与迭代器的实际位置进行比较。
第 18 行:for (auto it = this->msg.begin(); this->msg.begin() != this->msg.end(); it++)
应该
for (auto it = this->msg.begin(); it != this->msg.end(); it++)
您得到的错误是因为您一遍又一遍地比较同一件事,循环将继续迭代(增加迭代器),并且它尝试取消引用无效的迭代器。
你在第 39 行犯了同样的错误。
推荐阅读
- html - r markdown:数据框(或data.table)超出页面
- javascript - from openpyxl.chart.title import Title - AttributeError: 'list' object has no attribute
- r - 将数据帧的子集从字符转换为数字
- javascript - 为什么 event.preventDefault() 不适用于使用 jquery 加载的 html 元素
- qt - 树视图的 currentChanged 信号不调用槽函数
- android - 如何在Android中返回值之前确保侦听器已完成
- mongodb - 为单机 MongoDB 设置分发 MongoDB 后台索引创建
- scala - 为案例类自动生成案例对象
- ruby-on-rails - Rails Sanitizer Loofah gem 删除 `<` 后的文本
- java - JavaFX WebView ScrollEvent listener zooms in and scrolls. Only want it to zoom in