本文学习自 狄泰软件学院 唐佐林老师的 C++课程
实验1:用 class 定义类时,所有成员的默认访问级别是 private
#include <stdio.h>
struct A
{
// defualt to public
int i;
// defualt to public
int getI()
{
return i;
}
};
class B
{
// defualt to private
int i;
// defualt to private
int getI()
{
return i;
}
};
int main()
{
A a;
B b;
a.i = 4;
printf("a.getI() = %d\n", a.getI());
b.i = 4;
printf("b.getI() = %d\n", b.getI());
return 0;
}
mhr@ubuntu:~/work/c++$ g++ 16-1.cpp
16-1.cpp: In function ‘int main()’:
16-1.cpp:17:9: error: ‘int B::i’ is private
int i;
^
16-1.cpp:34:7: error: within this context
b.i = 4;
^
16-1.cpp:19:9: error: ‘int B::getI()’ is private
int getI()
^
16-1.cpp:36:38: error: within this context
printf("b.getI() = %d\n", b.getI());
^
mhr@ubuntu:~/work/c++$
改:
#include <stdio.h>
struct A
{
// defualt to public
int i;
// defualt to public
int getI()
{
return i;
}
};
class B
{
public:
// defualt to private
int i;
// defualt to private
int getI()
{
return i;
}
};
int main()
{
A a;
B b;
a.i = 4;
printf("a.getI() = %d\n", a.getI());
b.i = 4;
printf("b.getI() = %d\n", b.getI());
return 0;
}
mhr@ubuntu:~/work/c++$ g++ 16-1.cpp
mhr@ubuntu:~/work/c++$ ./a.out
a.getI() = 4
b.getI() = 4
mhr@ubuntu:~/work/c++$