C++ nested class

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

參考連結

Nested Classes in C++

C++ friend class

发布了90 篇原创文章 · 获赞 9 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/keineahnung2345/article/details/104076158