【C & C++】C++中class关键字和struct关键字存在区别?

在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 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值