将对象传递给 main 中的函数的问题

Problem in passing object to an function in main

如何在主函数中传递对象。我想显示用户 1 向用户 2 和用户 2 向用户 1 背靠背发送和接收的消息,但是当我使用调用者对象调用函数时,它只显示用户 1 发送消息

请帮我解决这个问题。我不明白我在做什么,我可以在 Inbox class

sendMsg() 函数中制作一个单独的传递引用对象副本吗
#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 行犯了同样的错误。