2

こんにちは、istream& operator>> と混同しています。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 関数の代入演算子で新しい動的メモリ割り当てを使用するにはどうすればよいですか?

4

2 に答える 2

2

fromのnameデータ メンバをto に変更するだけで、もうオーバーライドする必要はありません :)class Employeeconst char*std::stringoperator=

動的割り当てをできるだけ避けることをお勧めします。自動保存期間を持つオブジェクトの使用を活用して、RAII イディオムについて詳しく学んでください。あなたのコードは読みやすくなり、メモリリークの影響を受けにくくなります:)

于 2013-03-14T01:50:31.463 に答える
0

Disclaimer: both solution are for educational purpose and I would not recommend to use it in any real program. If you need to solve homework with strict requirements, then that maybe ok:

First:

istream& operator>>(istream& is, Employee & e) {
    Employee tmp;
    tmp.name = new char[1024];
    is >> tmp.num >> tmp.rate >> tmp.name;
    e = tmp;
    return is;
}

Second - more ugly and more "effective" solution:

istream& operator>>(istream& is, Employee & e) {
    char buffer[1024];
    Employee tmp;
    tmp.name = buffer;
    is >> tmp.num >> tmp.rate >> tmp.name;
    e = tmp;
    tmp.name = 0;
    return is;
}

Again both solution created under condition "to use existing assignment operator", real code should be different.

Note:

if (name != NULL) delete [] name;

is redundant, write

delete [] name;

instead

于 2013-03-14T02:09:20.713 に答える