gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:51:37 24 4
gpt4 key购买 nike

你好,所以我对我的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com