考试中遇到一道题,是静态数据成员受不受访问控制符的作用 有些疑惑,所以测试一下?
#include <iostream>
using namespace std;
class test
{
public:
static int i;
test() {}
void print();
protected:
static int h;
private:
static int j;
};
int test::i = 0;
int test::j = 0;
int test::h=0;
void test::print()
{
cout << "i = "<< i << endl;
cout << "j = "<< j << endl;
cout << "h= "<< h << endl;
}
int main()
{
test t;
t.print();
cout << "i = "<< t.i << endl;//对比参照项3
cout << "j = "<< t.j << endl;//测试是否可以不受private作用
cout << "h = "<< t.h << endl;//测试是否可以不受protected作用
return 0;
}
在linux编译不能通过:提示如下错误:

将protected 注释掉:


博客探讨了C++中静态数据成员是否受到访问控制符的影响。通过实验,作者发现静态成员变量确实会受到protected和private控制,导致在不同访问级别下编译结果不同。
最低0.47元/天 解锁文章
3146

被折叠的 条评论
为什么被折叠?



