2013-04-23 97 views
0

使用我已經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; 
} 

其中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)。 但我想不通,怎麼寫才能夠編譯它,並獲得正確的價值觀......

+0

向我們展示'Computer'類。 – 0x499602D2 2013-04-23 22:11:42

+0

與標題相反,我沒有看到任何虛函數,只有一個'operator <<'過載。 – 2013-04-23 22:14:09

+0

你的'getInfo'方法不返回任何東西。 – 0x499602D2 2013-04-23 22:15:51

回答

1

首先,爲什麼打印到名爲get_info的流的方法?說它put_info()(具有相同的返回類型/參數),並使用它像

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

不要忘記從put_info返回流。

而你做到這一點之後,它仍然是行不通的,因爲vector<Component>擁有精確組件 - 如果你在推一個CPU,它的殘酷截斷下來Component

+0

看來,你說得對。我可以編譯它,但是,我不能在'CPU'類中訪問該方法: - /我真的不明白爲什麼....也許我應該爲此創建新帖子.. – Dworza 2013-04-23 22:24:19

0

但是,當我想通過cout<<os打印出來;它只打印出地址(即0x6c180484)。但我想不通,怎麼寫才能夠編譯它,並獲得正確的價值觀......

我猜你是傳遞一個指針你的對象來std::cout,即獲取打印作爲它的地址(十六進制數字)。如果你有一個指針,請務必將其傳遞到流時去引用它:

std::cout << *pointer; 
1

此:

os << c.listOfComponents[i].getInfo(os) << endl; 

應該是:

c.listOfComponents[i].getInfo(os) << endl; 

這是當然的假設os返回std::ostream對象。


用這種方法,你打印一個指針,它返回它的地址(十六進制)。