我一直在为OOP类进行社交网络模拟项目,并遇到了上述错误。由于我还是C ++的新手,因此内存管理使我有些困惑。
自从我将Visual Studio(Windows)用于我的IDE以来,我已经尝试使用提供的调试方法来查明问题所在。
尽管我无法查明导致内存损坏的原因。
代码:
User.h
#pragma once
class Message;
#include "Message.h"
#include <list>
#include <map>
class User
{
private:
std::string u_name;
std::string u_email;
std::list<User> friend_list;
// std::list<FriendRequest> sent_Req;
// std::list<FriendRequest> rec_Req;
// std::unique_ptr<Wall> my_Wall;
public:
User() = delete;
User(const std::string& name, const std::string& email);
virtual ~User();
void send_friend_request();
//void accept_frnd_reqst(FriendRequest fr);
//void deny_frnd_reqst(FriendRequest fr);
void deletefriend(User usr);
void publ_msg_to_wall(/* Wall* to_wall */);
void publ_msg_reply(Message* to_msg);
void like_msg(Message* liked_msg);
std::map<User, std::list<User>> frnd_list();
void set_uname(std::string uname);
void set_uemail(std::string email);
std::string get_uname();
std::string get_uemail();
};
User.cpp
#include "pch.h"
#include "User.h"
#include <iostream>
User::User(const std::string & name, const std::string& email)
: u_name(name),u_email(email),wall(15)
{
}
User::~User()
{
}
void User::send_friend_request()
{
//Should create a friend request instance
//and add it to the list :
//of received requests of desired user
//of sent requests from this user.
}
void User::publ_msg_to_wall(/* Wall* to_wall */)
{
User* publ = this;
std::string txt;
getline(std::cin, txt);
Message tmp_msg(publ, txt);
// now publish that to the specified wall :
// add it to specified wall's list of messages.
// to_wall->post(tmp_msg)
// NOTE: Make sure to copy it! we dont want to lose the message once the function goes out of scope.
std::cout << "Done." << std::endl;
}
Message.h
#pragma once
#include "User.h"
//#include "ReplyMessage.h"
#include <string>
#include <chrono>
#include <list>
class Message
{
private:
time_t timestamp;
std::string msg_txt;
std::unique_ptr<User> msg_creator;
// std::unique_ptr <ReplyMessage> next_reply;
int like_counter;
std::list<User> likedfrom;
public:
Message() = delete;
Message(User* wr_user, std::string txt);
virtual ~Message();
void toString();
};
Message.cpp
#include "pch.h"
#include "Message.h"
Message::Message(User* wr_user, std::string txt)
:msg_txt(txt),msg_creator(wr_user)
{
timestamp = time(0);
}
Message::~Message()
{
}
主要
#include "pch.h"
#include <iostream>
#include "Message.h"
#include "User.h"
int main()
{
User user1("john","sss");
user1.publ_msg_to_wall();
std::cout << "Hello World!\n";
}
我猜想这与在函数Message
中初始化publ_msg_to_wall
对象有关。
这是因为错误发生在程序输出Hello World
之前。
如果有人告诉我如何“保持”或复制在Message
函数中创建的publ_msg_to_wall
的实例,也将不胜感激。