Passing and storing a const reference via a constructor?

前端 未结 1 1183
野趣味
野趣味 2021-02-07 10:02

This is probably a simple question, but I\'m stuck on it. I\'m trying to pass an object down from ObjectA to ObjectB (which is a member of ObjectA) via it\'s constructor. Howeve

相关标签:
1条回答
  • 2021-02-07 10:45
    class    ClassB
    {
        private:
            const int&    internalX;
        public:
            ClassB(const int& tempX);
    }
    
    ClassB::ClassB(const int& tempX):
         internalX(tempX)
    {
    }
    

    As you said, a reference has to be initialized immediately. Thus, if you want your reference to be a class member, you have to use your constructor's initialization list to set it.

    (This short explanation might also make things clearer for you, as it is specifically centered on the situation you've just met)

    Good luck

    0 讨论(0)
提交回复
热议问题