我遇到函數,而不是重載操作< <與COUT使用,聲明一個函數,它接受一個ostream並返回一個ostream聲明一個接受和返回「ostream&」而不是重載operator <<的函數有什麼用?
例子:
#include <iostream>
class A {
private:
int number;
public:
A(int n) : number(n) {}
~A() {}
std::ostream& print(std::ostream& os) const;
friend std::ostream& operator<<(std::ostream& os, const A a);
};
實施的例子:
std::ostream& A::print(std::ostream& os) const {
os << "number " << number;
return os;
}
std::ostream& operator<<(std::ostream& os, const A a) {
os << "number " << a.number;
return os;
}
現在,如果我跑這我可以在不同情況下使用不同的功能,例如..
int main() {
A a(1);
std::cout << "Object."; a.print(std::cout);
std::cout << "\n\n";
std::cout << "Object." << a;
std::cout << "\n\n";
return 0;
}
輸出:
Object.number 1
Object.number 1
似乎沒有要在那裏將需要打印功能,因爲你只能單獨或在「COUT鏈」的開始使用,但從來沒有的情況在它的中間或末尾,這可能使它無用。不是(如果找不到其他用途)最好使用「void print()」函數嗎?
使用是真的讓我煩惱。我看不到任何有效的理由。 –
這不完全正確。你可以嵌套函數而不是鏈接它。 'a.print(std :: cout <<「Object。」);' – mydogisbox
我會非常厭惡'a。在「之後」打印(a.print(std :: cout <<「之前」)<<「之間)」「之後」;「。雖然。 – MSalters