1. C++类的属性默认访问权限
如果没有在类中设置属性和方法的访问权限,那么默认访问权限是private。
#include <iostream>
using namespace std;
class A{
int a;
int func(){
return 0;
}
};
int main(int argc, char *arg[])
{
A obj;
obj.a = 1;
obj.func();
return 0;
}
||=== 构建文件: "无目标" 在 "无项目" 中 (编译器: 未知的) ===|
StruCla.cpp||In function 'int main()':
StruCla.cpp|4|error: 'int A::a' is private
StruCla.cpp|12|error: within this context
StruCla.cpp|5|error: 'int A::func()' is private
StruCla.cpp|13|error: within this context
||=== 构建 失败: 4 error(s), 0 warning(s) (0 分, 0 秒) ===|
2. C++ struct的成员默认访问权限是public
#include <iostream>
using namespace std;
struct B{
int b;
char c;
B()
{
b = 2;
c = 'S';
}
~B()
{
b = 0;
}
int func()
{
b = 10;
cout << c << endl;
}
};
int main()
{
B SctObj;
cout << SctObj.b << endl;
SctObj.func();
return 0;
}
无错误输出:
3. C++中的 struct 和 class 有什么区别?
(1) 默认继承权。class的默认继承权是private,而struct默认继承权是public。
(2) 成员默认访问权限。class默认访问权限是private,struct默认是public。
除了上面两点,其他没什么区别,语法都一样。
4. C++ struct和C struct的区别
Protection行为 能否定义函数 C 无 否,但可以有函数指针 C++ 有 可以,默认是public
这个protection行为个人认为就是成员是否具有访问权限