我有一个类似于这样的用户:
class User
{
private:
char* p_username;
int nProcesses;
struct time
{
int mins;
int secs;
} totalTime;
int longestPID;
char* p_longestPath;
public:
User();
User(const char[],int,int,int,const char[]);
~User();
User operator=(const User&);
// Other functions
};
重载的赋值运算符函数是:
User User::operator=(const User &u)
{
if (this != &u)
{
delete [] p_username;
delete [] p_longestPath;
p_username = new char[strlen(u.p_username)+1];
strcpy(p_username,u.p_username);
nProcesses = u.nProcesses;
totalTime.mins = u.totalTime.mins;
totalTime.secs = u.totalTime.secs;
longestPID = u.longestPID;
p_longestPath = new char[strlen(u.p_longestPath)+1];
strcpy(p_longestPath,u.p_longestPath);
}
return *this;
}
使用赋值运算符的示例主程序:
int main()
{
cout << "\n\nProgram\n\n";
User u("Username",20,30,112233,"Pathname"),u2;
u2 = u;
}
当我尝试在行u2 = u中使用赋值运算符时,除了动态字符数组之外,所有内容都被正确分配。
来自operator =函数末尾的测试输出显示,在赋值结束时,一切都完美无缺(用户名和路径名都是正确的),但是在赋值后直接测试主函数的输出显示所有突然,char数组发生了变化。突然,u2的用户名为空,路径名的前半部分为垃圾。
如果在赋值运算符函数的末尾,用户名和路径名是完美的,那么它们如何在调用函数中出错呢?
这真让我难过......
编辑:这是构造函数
User::User()
{
p_username = 0;
nProcesses = 0;
totalTime.mins = 0;
totalTime.secs = 0;
longestPID = -1;
p_longestPath = 0;
}
User::User(const char UID[],int minutes,int seconds,int PID,const char path[])
{
p_username = new char[strlen(UID)+1];
strcpy(p_username,UID);
nProcesses = 1;
totalTime.mins = minutes;
totalTime.secs = seconds;
longestPID = PID;
p_longestPath = new char[strlen(path)+1];
strcpy(p_longestPath,path);
}
答案 0 :(得分:3)
您将从赋值函数返回值。您的复制构造函数可能存在缺陷。
答案 1 :(得分:0)
您可以在此处查看本教程: http://courses.cms.caltech.edu/cs11/material/cpp/donnie/cpp-ops.html
以下是一个例子:
MyClass& MyClass::operator=(const MyClass &rhs) {
// Only do assignment if RHS is a different object from this.
if (this != &rhs) {
... // Deallocate, allocate new space, copy values...
}
return *this;
}