【问题标题】:Problem in passing object to an function in main将对象传递给main中的函数的问题
【发布时间】:2021-09-03 09:48:18
【问题描述】:

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

请帮我解决这个问题。我不明白我在做什么,我可以在Inbox 类中的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;
}

【问题讨论】:

  • 请不要为整个段落使用粗体。谢谢。
  • 好的,谢谢你的建议
  • 你能分享这个特定代码的输出吗?

标签: c++ object oop message


【解决方案1】:

问题在于,在第 18 行中,您将 this-&gt;msg.begin() 与末尾进行比较,而不是与迭代器的实际位置。

第 18 行:for (auto it = this-&gt;msg.begin(); this-&gt;msg.begin() != this-&gt;msg.end(); it++)

应该是

for (auto it = this-&gt;msg.begin(); it != this-&gt;msg.end(); it++)

您得到的错误是因为您一遍又一遍地比较同一事物,循环将继续迭代(增加迭代器),并且它尝试取消引用无效的迭代器。

你在第 39 行犯了同样的错误。

【讨论】:

  • 非常感谢 thomas 的回复
猜你喜欢
  • 2022-01-16
  • 2014-03-21
  • 1970-01-01
  • 1970-01-01
  • 2012-03-03
  • 2011-12-14
  • 2020-02-23
  • 2014-06-05
  • 1970-01-01
相关资源
最近更新 更多