C++ nested class

C++ nested class

nested class

In TensorRT/samples/common/logging.hthe, TestAtomis defined Loggerin:

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;
    }
};

We put the outer class called enclosing class, the inner layer is called the nested class.

nested class have the same access to member variables of other enclosing class (and therefore nested class can access private members of enclosing class variables); enclosing class is no special access for nested class, and therefore can not be accessed directly nested class the private member variables.

And we're Logger::reportTestStartto see: the testAtomprivate member variable objects mStartedthat can be Loggeraccessed, which is what causes it? See C ++ Friend class .

Reference Links

Nested Classes in C++

C++ friend class

Published 90 original articles · won praise 9 · views 50000 +

Guess you like

Origin blog.csdn.net/keineahnung2345/article/details/104076158