您好,我对 istream& 运算符感到困惑>>。我必须重载此运算符才能获取对 C 字符串使用动态内存分配的类的输入。
我的 Employee.h 文件是
#include <iostream>
using namespace std;
const double MIN_WAGE = 10.25;
class Employee {
int num;
char * name;
double rate;
public:
Employee();
Employee(const Employee&);
Employee operator=(const Employee&);
friend istream& operator>>(istream& is, Employee& employee);
friend ostream& operator<<(ostream& is, const Employee& employee);
friend bool operator>(const Employee& a, const Employee& b);
~Employee();
};
我有一个称为赋值运算符的复制构造函数
Employee::Employee(const Employee & e) {
name = NULL;
*this = e;
}
Employee Employee::operator=(const Employee & e) {
if (this != e) {
num = e.num;
rate = e.rate;
if (name != NULL) delete [] name;
if (e.name != NULL) {
name = new char[strlen(e.name) + 1];
strcpy(name, e.name);
}
else name = NULL;
}
return *this;
}
在赋值运算符中,我为我正在使用的 C 字符串的长度动态分配了内存。到目前为止我的 istream 功能:
istream& operator>>(istream& is, Employee & e) {
int n;
double r;
}
我的问题是:如何在 istream 函数的赋值运算符中使用新的动态内存分配?
最佳答案
只需将 class Employee
的 name
数据成员从 const char*
更改为 std::string
并您将不再需要覆盖 operator=
:)
请注意,尽可能避免动态分配是一个很好的做法。尝试利用具有自动存储持续时间的对象并了解有关 RAII idiom 的更多信息。您的代码将变得更易于阅读并且不易受到内存泄漏的影响:)
关于c++ - 使用动态内存分配重载 istream 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15399729/