用于 ostream 的重载<<运算符,用于虚函数
Overloaded << operator for ostream, used in virtual functions
我的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;
}
其中CCD_ 2是CCD_。
我的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>
精确地保存着Components——如果你推一个CPU
,它就会被残酷地截断为Component
。
这:
os << c.listOfComponents[i].getInfo(os) << endl;
应该是:
c.listOfComponents[i].getInfo(os) << endl;
这当然是假设os
返回std::ostream
对象。
按照你的方式,你打印了一个指针,它返回它的地址(十六进制(。
但是,当我想通过
cout<<os
打印出来时;它只打印出地址(即0x6c180484(。但我不知道如何编写它,以便能够编译它并获得正确的值。。。
我猜您正在将对象的指针传递给std::cout
,该指针将打印为其地址(十六进制数(。如果您有一个指针,请确保在将其传递到流时取消引用:
std::cout << *pointer;
相关文章:
- 1d 智能指针不适用于语法 (*)++
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 用于访问容器<T>数据成员的正确 API
- 重载操作程序时出错>>用于类中的字符串 memebr
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 如何防止 c++ 在从浮点型转换为双精度型(不适用于 IO)时添加额外的小数?
- C++中的cin.ignore()函数不适用于整个流
- 没有用于初始化C++中的变量模板的匹配构造函数
- 呼叫运营商<<临时
- 用于C++中带有数组和指针的循环
- 为什么它不适用于Visual 2019的原因
- 使用在用于SFINAE的void_t中具有参数的方法
- 在createdialog创建的窗口中捕获用于编辑控件的OnMouseMove消息
- 过载输出<<用于类的运算符,以打印其中的元组
- 重载运算符<<用于模板类.即使使用好友关键字也无法获得私人会员
- 如何过载<<用于YAML::Emitter的运算符,以序列化包含另一个自定义类的向量的自定义类
- 重载运算符<<用于ostream语法
- 运算符<<(ostream&os,..)用于模板类
- 重载& lt; & lt;用于打印自定义异常的操作符
- Can运算符<<用于设计我们自己的输出显示方式