使用我已經overloaded << opreator
這樣:重載<<運算符的ostream,在虛函數
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)。 但我想不通,怎麼寫才能夠編譯它,並獲得正確的價值觀......
向我們展示'Computer'類。 – 0x499602D2 2013-04-23 22:11:42
與標題相反,我沒有看到任何虛函數,只有一個'operator <<'過載。 – 2013-04-23 22:14:09
你的'getInfo'方法不返回任何東西。 – 0x499602D2 2013-04-23 22:15:51