[英]Overriding ofstream operator<<
為什么我仍然有ERROR:在下面一行的std::ofstream << val
注意了一個標識符 ? MSVC。
std::ostream& operator<< (bool val) { m_lock.lock(); std::ofstream << val; m_lock.unlock(); return *this; }
class OfstreamLog : public std::ofstream {
private:
std::mutex m_lock;
public:
OfstreamLog() : std::ofstream() { }
explicit OfstreamLog(const char* filename, ios_base::openmode mode = ios_base::out) : std::ofstream(filename, mode) { }
std::ostream& operator<< (bool val) { m_lock.lock(); std::ofstream << val; m_lock.unlock(); return *this; }
std::ostream& operator<< (short val);
std::ostream& operator<< (unsigned short val);
std::ostream& operator<< (int val);
std::ostream& operator<< (unsigned int val);
std::ostream& operator<< (long val);
std::ostream& operator<< (unsigned long val);
std::ostream& operator<< (float val);
std::ostream& operator<< (double val);
std::ostream& operator<< (long double val);
std::ostream& operator<< (void* val);
std::ostream& operator<< (std::streambuf* sb);
std::ostream& operator<< (std::ostream& (*pf)(std::ostream&));
std::ostream& operator<< (std::ios& (*pf)(std::ios&));
std::ostream& operator<< (ios_base& (*pf)(ios_base&));
};
std::ofstream
是一個類型名稱。 沒有任何對象,您無法為其調用非靜態方法或運算符。
在這種情況下,您可能需要std::ofstream::operator<<(val);
而不是std::ofstream << val;
。
說明:
當你想從子類的方法調用父類的方法時,你這樣做:
class A
{
void func() {}
};
class B
{
void test()
{
func(); // Like this
}
};
但是如果子類具有相同名稱的方法(更確切地說,具有相同的簽名 (它意味着相同的名稱和參數類型)),則將調用它而不是父類的方法。 要顯式調用父類的方法,可以使用以下語法:
class A {...};
class B
{
void test()
{
A::func(); // Notice `A::`
}
};
現在讓我們談談運營商。 當你想調用一個操作符時,你通常會使用一個對象名,就像object << 10;
。 但是當你想從這個類的方法調用一個類(或它的父類)的operator
,你應該使用完整的operator
語法:
class A
{
operator<<(int){}
};
class B
{
void test()
{
operator<<(10); // <-----
*this << 10; // Also you can do it like this
}
};
現在,我們將這兩種技術結合起來:
如果子類具有與父項一致的運算符,並且您想要調用父項的運算符,則執行以下操作:
class A {...};
class B
{
void test()
{
A::operator<<(10); // Notice `A::`
*(A*)this << 10; // Also you can do it like this
}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.