在C++开发中其实我们可以使用struct关键字定义类,也可以使用class.
唯一区别是, struct 和 class的默认访问权限不太一样.
对于C++的类,我们可以在第一个访问说明符之前定义成员,对于这种成员的访问权限依赖于类定义的方式.
如果我们使用struct关键字,则定义在第一个访问说明符之前的成员是public;与之相反,如果我们使用class关键字,则这些成员是private,
示例代码如下
使用class定义类test
#include <iostream>
class test{
int b;
public:
int a;
void show(){
std::cout << "hello" << std::endl;
};
};
int main(int argc, char* argv[]){
test t;
t.show();
std::cout << t.b << std::endl;
return 0;
}
编译结果如下,
➜ C++ g++ test.cpp
test.cpp: In function ‘int main(int, char**)’:
test.cpp:16:20: error: ‘int test::b’ is private within this context
std::cout << t.b << std::endl;
^
test.cpp:4:9: note: declared private here
int b;
^
如上所示,编译报错,test中的变量b为private.
使用struct定义类test,
#include <iostream>
struct test{
int b;
public:
int a;
void show(){
std::cout << "hello" << std::endl;
};
};
int main(int argc, char* argv[]){
test t;
t.show();
std::cout << t.b << std::endl;
return 0;
}
编译结果如下,
➜ C++ g++ test.cpp