我有overloaded << opreator
这种方式:
ostream& operator<<(ostream&os, const Computer& c) {
for (int i = 0; i != c.listOfComponents.size() - 1; i++) {
os << c.listOfComponents[i].getInfo(os) << endl;
}
return os;
}
listoOfComponents
在哪里vector<Component>
。
我的Component
班级和其中一个孩子班级在这里:
class Component {
public:
Component() {
};
~Component() {
};
virtual ostream &getInfo(ostream& os)const;
};
ostream &Component::getInfo(ostream& os)const {
return os;
}
class CPU : public Component {
public:
CCPU(int cores, int freq) {
this->cores = cores;
this->freq = freq;
};
~CPU() {
};
virtual ostream &getInfo(ostream& os)const;
int cores;
int freq;
};
ostream &CPU::getInfo(ostream& os)const {
os<<"CORES:"<<cores<<" FREQ:"<<freq<<endl;
}
最后是Computer
课程:
class Computer {
public:
// constructor
Computer(string name) {
this->name = name;
};
// destructor
~Computer() {
};
// operator <<
friend ostream& operator<<(ostream& os, const CComputer& c);
CComputer & AddComponent(Component const & component) {
this->listOfComponents.push_back(component);
return *this;
};
CComputer & AddAddress(const string & address) {
this->address = address;
return *this;
};
string name;
string address;
vector<Component> listOfComponents;
};
但是,当我想通过cout<<os;
它打印出来时,它只打印出地址(即0x6c180484)。但我不知道如何编写它才能编译它并获得正确的值......