【发布时间】:2014-12-15 05:17:26
【问题描述】:
我想在 STL 映射中添加类对象作为 C++ 中的值。就像std::map<CString,class myClass*>myMap。但是编译器向我展示了这样做的错误。我是否必须为该类实现所有比较运算符重载?如果没有,那么我该如何实现呢?
代码如下:
// 头文件
#pragma once
#include "afxsock.h"
#include"NetworkDataProcessor.h"
#include"MainFrm.h"
#include"ChattingDialog.h"
#include<map>
using namespace std;
class CConnectionManager :public CAsyncSocket
{
public:
static CConnectionManager *GetClientInstance();
BOOL ClientSignIn(CString, CString);
void ConnectToServer();
public:
CString m_sendBuffer;
int m_nBytesSent;
int m_nBytesBufferSize = MAX_BUFFER_SIZE;
virtual void OnClose(int nErrorCode);
virtual void OnConnect(int nErrorCode);
virtual void OnReceive(int nErrorCode);
virtual void OnSend(int nErrorCode);
public:
std::map<CString, CChattingDialog* >ChatWindows;
private:`enter code here`
CConnectionManager();
~CConnectionManager();
static CConnectionManager * client_instance;
};
// cpp文件函数:
void CMyMessangerView::OnClientListClick(NMHDR* pnmh, LRESULT* pResult)
{
DWORD dwPos = ::GetMessagePos();
CPoint point((int)LOWORD(dwPos), (int)HIWORD(dwPos));
GetListCtrl().ScreenToClient(&point); int nIndex; if ((nIndex = GetListCtrl().HitTest(point)) != -1)
{
CString string = GetListCtrl().GetItemText(nIndex, 0);
CChattingDialog chatingDlg;
chatingDlg.SendToUser = string;
CString user = chatingDlg.UserRealName(string);
CConnectionManager *client = CConnectionManager::GetClientInstance();
client->ChatWindows.insert(pair<CString, CChattingDialog *>(user, &chatingDlg));
UpdateData(FALSE);
chatingDlg.DoModal();
}
*pResult = 0;
}
错误: 15 IntelliSense:没有重载函数实例“std::map<_kty _ty _pr _alloc>::insert [with _Kty=CString, _Ty=CChattingDialog *, _Pr=std::less, _Alloc=std::allocator> ]" 匹配参数列表 参数类型是:(std::pair) 对象类型为:std::map, std::allocator>
错误 3 错误 C2976:'std::map':模板参数太少 c:\projects\poc\mymessanger\mymessanger\clientconnection.h 25 1 MyMessanger
错误 4 错误 C2665: 'std::pair::pair' : 3 个重载都不能转换所有参数类型 c:\projects\poc\mymessanger\mymessanger\mymessangerview.cpp 131 1 MyMessanger 16 IntelliSense:没有构造函数实例“std::pair<_ty1 _ty2>::pair [with _Ty1=CString, _Ty2=CChattingDialog &]”与参数列表匹配 参数类型为: (CString, CChattingDialog *) c:\Projects\POC\MyMessanger\MyMessanger\MyMessangerView.cpp 131 29 MyMessanger 等等......还有一些错误,比如表示相同
【问题讨论】:
-
向我们展示代码和确切的错误消息。
-
std::map
myMap. “class myClass”看起来很奇怪。为什么要添加“类”。 -
我需要收集此类对象以及作为字符串的键。我想根据一些字符串类型的键来获取该类的对象。
-
@MahendraChhimwal 除了语法错误(仍然不清楚哪一行有错误)之外,您正在将指针存储到映射中的局部变量。这些变量在它们声明的块之外不存在,所以这段代码有问题:
client->ChatWindows.insert(pair<CString, CChattingDialog *>(user, &chatingDlg) -
另外,不要发布 Intellisense 错误。发布编译器错误。