如何使用重载>> <<到构成 ojbect 部门(部门**)的指针数组

how to use overloading >> << to array of pointers which consitst ojbect Departments (Departments**)

本文关键字:部门 lt gt 数组 指针 重载 何使用 ojbect      更新时间:2023-10-16

Department class '#include #include #pragma 一次

using namespace std;
class Department
{
// overload input output streams
    friend ostream &operator<<(ostream &, const Department &);
    friend istream &operator>>(istream &, Department &);
private:
    string name;
    long id;
public:
    static int departmentsCounter; // count num of elements
    Department();
    // set get block
    void setId(long);
    void setName(string);
    string getName() { return name; }
    long getId() { return id; }
    // overload block 
    Department &operator=(const Department &); // instead copy constructor
    bool operator>(const Department &) const; // check if count of students greater than count of students in another department
    void operator+=(Department &); // add new course to course list of the student
    void operator=(Department &); // remove course from course list of the student
    ~Department();
};`

部门 CPP

#include "Department.h"
int Department::departmentsCounter = 0;
Department::Department()
{
    name;
    id = 0;
}
void Department::setId(long _id)
{
    id = _id;
}
void Department::setName(string _name)
{
    name = _name;
}
// overload out put (without cource list)
ostream &operator<<(ostream &output, const Department &s)
{
    output << "Department: nName " << s.name << "nid " << s.id << "n-------------------------------------------------n";
    return output;
}
// overload input without check of right input data
istream &operator>>(istream &input, Department &s) {
    cout << "nEnter name: ";
    input >> s.name;
    cout << "nEnter id: ";
    input >> s.id;
    return input;
}
Department &Department::operator=(const Department &s) {
    Department temp;
    name = s.name; 
    id = s.id;
    return temp;
}

Department::~Department()
{}

在主函数中使用此 cout << *(departments_list)[size];但它不起作用 内存错误 所以我不知道如何解决它。也许我应该在构造函数中分配内存,但我不知道我像名字一样使用的字符串长度。实际上我的问题是如何使用运算符重载到**部门,因为我不明白这边是如何工作的

如果你有一个或指针向量,正确的语法是:

cout << *(departments_list[size]);

*注意()的位置变化。

注意:以上假设size是数组或向量限制内的索引变量。