gpt4 book ai didi

c++ - ostream 的重载 << 运算符,用于虚函数

转载 作者:行者123 更新时间:2023-11-28 03:18:24 27 4
gpt4 key购买 nike

我已经 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;
}

哪里listoOfComponentsvector<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)。但我不知道如何编写它才能编译它并获得正确的值...

最佳答案

首先,为什么打印到流的方法叫做get_info ?叫它put_info() (具有相同的返回类型/参数)并像使用它一样

c.listOfComponents.put_info(os) << endl;

不要忘记从 put_info 返回流.

在你这样做之后,它仍然不起作用,因为vector<Component>恰好包含组件——如果你按下一个 CPU中,它被残酷地截断为 Component .

关于c++ - ostream 的重载 << 运算符,用于虚函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16180027/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com