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

Overloaded << operator for ostream, used in virtual functions

本文关键字:用于 lt 函数 运算符 ostream 重载      更新时间:2023-10-16

我的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;