Accessibility of data member in member function before declaration of data member

試著忘記壹切 提交于 2019-12-25 05:14:06

问题


Consider this code:

class Test
{
public:

Test() { i = 0;  }

private:

int i;
};

Data member 'i' is used even before it is declared/defined. Should this not be a compilation error ? (It compiled fine!!!)


回答1:


The rule is that member functions defined in the class definition are compiled as if they were defined immediately after the class definition.




回答2:


No it shouldn't, within the context of the class definition, all members, data members or functions have complete visibility.




回答3:


where is the data member used before declaration?

class Test
{
public:

Test() { i = 0;  } // constructor

private:

int i;  //datamemeber
};
main()
{
Test obj; // memory allocated only here
}

the constructor is called after only the obj is created in main. then the memory for i is allocated. and the the constructor is called so there is scope and visibility for i



来源:https://stackoverflow.com/questions/9783473/accessibility-of-data-member-in-member-function-before-declaration-of-data-membe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!