如何在主函式中傳遞物件。我想顯示用戶1向用戶2和用戶2向用戶1發送和接收的資訊,但當我使用呼叫者物件呼叫一個函式時,只顯示用戶1發送的味精
。請幫助我解決這個問題。我不明白我在做什么,我是否可以在Inbox類中的sendMsg()函式中傳遞參考的物件做一個單獨的副本
#include<bit/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:
訊息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(){
收件箱用戶1,用戶2。
user1.sendMsg(user2, "hello") 。
user1.showSendMsg()。
user2.sendMsg(user1, "Hi")。
user2.showRecievedMsg()。
user1.sendMsg(user2, "你在做什么?")。
user1.showSendMsg()。
user2.sendMsg(user1, "沒什么!!")。
user2.showRecievedMsg()。
user1.sendMsg(user2, "你在嗎?")。
user1.showSendMsg()。
user2.sendMsg(user1, "I am lil bit buzy") 。
user2.showRecievedMsg()。
return 0;
uj5u.com熱心網友回復:
問題是在第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行也犯了同樣的錯誤。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/313409.html
標籤:
