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

时间:2016-04-27 14:25:28

标签: c++ visual-studio

系班    `的#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()
{}

在main函数中使用它  cout << *(departments_list)[size]; 但它没有工作内存错误母猪我知道如何解决它。也许我应该在构造函数中分配内存,但我不知道我使用的字符串的长度就像一个名字。 Actualy我的问题是如何使用运算符重载到**部门,因为我不明白它是如何工作的

1 个答案:

答案 0 :(得分:0)

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

cout << *(departments_list[size]);

*请注意()的位置变化。

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