C++ nested class
nested class
在TensorRT/samples/common/logging.h
中,TestAtom
被定義在Logger
中:
class Logger : public nvinfer1::ILogger
{
public:
//!
//! \brief Opaque handle that holds logging information for a particular test
//!
//! This object is an opaque handle to information used by the Logger to print test results.
//! The sample must call Logger::defineTest() in order to obtain a TestAtom that can be used
//! with Logger::reportTest{Start,End}().
//!
class TestAtom
{
public:
TestAtom(TestAtom&&) = default;
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;
}
};
我們把外層的class稱為enclosing class,內層的稱為nested class。
nested class擁有與其它enclosing class的成員變數同樣的存取權限(因此nested class可以存取enclosing class的私有成員變數);enclosing class則對nested class沒有特殊的存取權限,因此無法直接存取nested class的私有成員變數。
但是我們卻在Logger::reportTestStart
中看到了:testAtom
物件的私有成員變數mStarted
是可以被Logger
所存取的,這是什麼原因呢?詳見C++ friend class。