编辑:完整程序https://onecompiler.com/cpp/3z5p2rpgk 我有一个指向 MailServer 类中 CMail 对象链接列表的指针数组。 (CMail **m_Sent;)
在 sendMail() 函数中,我将复制对象并在字段 (m_Sent) 中添加指向它的链接 - 如果它不在字段中。
如果字段 (m_Sent) 中已经存在同名链接,我将遍历同名项目 (m_From item) 上的链表到列表末尾,并在那里添加对象。
函数,但是它不能正常工作,你会注意到它变成了 sendMail 函数的索引 0。
class CMail
{
public:
CMail (const char *from, const char *to, const char *body);
CMail(const CMail &src);
~CMail();
CMail& operator = (CMail &&src) noexcept;
bool compareByFrom(const CMail &x) const;
void setNext(CMail &x);
CStr getFrom() const;
CMail *getLast();
private:
CStr m_From;
CStr m_To;
CStr m_Body;
CMail *m_Next;
};
CMail::~CMail()
{
}
CMail::CMail (const char *from, const char *to, const char *body)
: m_From(from),
m_To(to),
m_Body(body),
m_Next(nullptr)
{
}
CMail::CMail(const CMail &src)
: m_From(src.m_From),
m_To(src.m_To),
m_Body(src.m_Body),
m_Next(src.m_Next)
{
}
CMail& CMail::operator = (CMail &&src) noexcept
{
if(this == &src)
return *this;
m_From = src.m_From;
m_To = src.m_To;
m_Body = src.m_Body;
m_Next = src.m_Next; // mozna chyba
return *this;
}
bool CMail::compareByFrom(const CMail &x) const
{
if(m_From == x.m_From)
return true;
return false;
}
CMail *CMail::getLast()
{
CMail *tmp;
CMail *x;
while(tmp)
{
x = tmp;
tmp = tmp->m_Next;
}
return x;
}
void CMail::setNext(CMail &x)
{
m_Next = &x;
}
class CMailServer {
public:
CMailServer (void);
void sendMail (const CMail &m);
private: CMail **m_Sent;
};
CMailServer::CMailServer (void)
: m_Capacity_Sent(1000),
m_Capacity_Acept(1000),
m_Len_Sent(0),
m_Len_Acept(0)
{
m_Sent = (CMail**) malloc(sizeof(CMail*)*m_Capacity_Sent);
m_Acept = (CMail**) malloc(sizeof(CMail*)*m_Capacity_Acept);
}
CMailServer::~CMailServer (void)
{
}
void CMailServer::sendMail (const CMail &m)
{
// nastaveni send
for(size_t i=0; i<m_Len_Sent; i++)
{
if(m_Sent[i]->compareByFrom(m))
{
CMail a = m;
m_Sent[i]->getLast()->setNext(a);
return;
}
}
CMail a = m;
m_Sent[m_Len_Sent++] = &a;
cout << "Zde: " << m_Sent[0]->getFrom() << endl;
}
int main ( void )
{ CMail a( "john", "M", "progtest deadline" );
CMail b( "peter", "N", "progtest deadline" );
CMailServer server;
server.sendMail(a); server.sendMail(b);
}