Does C++ have “with” keyword like Pascal?

后端 未结 17 854
傲寒
傲寒 2020-12-06 05:02

with keyword in Pascal can be use to quick access the field of a record. Anybody knows if C++ has anything similar to that?

Ex: I have a pointer with m

17条回答
  •  天命终不由人
    2020-12-06 05:14

    A simple way to do this is as follows

    class MyClass
    {
        int& m_x;
    
        public MyClass(int& x)
        {
            m_x = x;
            m_x++;
        }
    
        ~MyClass()
        {
            m_x--;
        }
    }
    int main():
    {
        x = 0;
        {
            MyClass(x)  // x == 1 whilst in this scope
        }
    }
    

    I've been writing python all day long and just scrapped this down before anyone takes me to the cleaners. In a larger program this is an example of how to keep a reliable count for something.

提交回复
热议问题