C++ friend class

C++ friend class

friend class

如果在類別A中將類別B定義為friend class,那麼類別B就有權存取類別A的privateprotected成員。

TensorRT/samples/common/logging.h中,Logger被定義為TestAtom的friend class,所以Logger類別的物件便有權限存取TestAtom物件的privateprotected成員:

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的原因。

參考連結

Friend class and function in C++

C++ nested class

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值