C++ friend class
friend class
如果在類別A中將類別B定義為friend class,那麼類別B就有權存取類別A的private
及protected
成員。
在TensorRT/samples/common/logging.h
中,Logger
被定義為TestAtom
的friend class,所以Logger
類別的物件便有權限存取TestAtom
物件的private
及protected
成員:
class Logger : public nvinfer1::ILogger
{
public:
class TestAtom
{
//...
private:
friend class Logger;
TestAtom(bool started, const std::string& name, const std::string& cmdline)
: mStarted(started)
, mName(name)
, mCmdline(cmdline)
{
}
bool mStarted;
std::string mName;
std::string mCmdline;
};
//...
//!
//! \brief Report that a test has started.
//!
//! \pre reportTestStart() has not been called yet for the given testAtom
//!
//! \param[in] testAtom The handle to the test that has started
//!
static void reportTestStart(TestAtom& testAtom)
{
reportTestResult(testAtom, TestResult::kRUNNING);
assert(!testAtom.mStarted);
testAtom.mStarted = true;
}
};
在上面這段代碼中,Logger
這個enclosing class原本是不能存取TestAtom
這個nested class的私有成員變數的。(關於enclosing class及nested class請參考C++ nested class)。
為了繞開這個限制,在TestAtom
中將Logger
定義為其friend class,如此一來,Logger
的成員函數便能自由地存取TestAtom
的私有成員變數了,這也是在Logger::reportTestStart
中,可以存取testAtom.mStarted
的原因。