c++ - 使用动态内存分配重载 istream 运算符

标签 c++ memory-management operator-overloading istream dynamic-allocation

您好,我对 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 Employeename 数据成员从 const char* 更改为 std::string 并您将不再需要覆盖 operator= :)

请注意,尽可能避免动态分配是一个很好的做法。尝试利用具有自动存储持续时间的对象并了解有关 RAII idiom 的更多信息。您的代码将变得更易于阅读并且不易受到内存泄漏的影响:)

关于c++ - 使用动态内存分配重载 istream 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15399729/

相关文章:

c++ - C++ 中 unsigned char 的 ostream 运算符重载

ruby - 重载! Ruby 中的运算符

c++ - 成员函数可以通过哪些方式相互比较?

c++ - MongoDB:查询单个随机文档的最有效方法是什么?

c++ - 这个阶乘程序中发生了什么?

macos - 帮助改进我针对 Safari 高内存使用率的个人解决方案,或说明为什么它不好

c - 使用 realloc 与 free -> malloc 函数的区别

c++ - 无法在 eclipse cdt 中构建 makefile

C++:在相等性测试中使用基类的私有(private)成员

c - 释放数据时内存泄漏?