C++ class 和 struct 区别

1 struct默认的数据访问控制是public的,class默认的访问控制是private的。

struct可以添加private/public修饰符,但是如果没有显式添加,则默认的访问权限为public,class默认为private。

2 C++中,struct也可以继承。但是,struct默认的继承访问权限是public的,而class是private。

3 使用大括号赋值。struct如果没有定义构造函数(是的,在C++中,struct也可以定义构造函数),可以使用大括号对struct的数据成员进行赋值。

class只有在成员变量全部是public的情况下,才能使用大括号进行赋值。

总结

1 类及对象,使用class, 便于分权限封装;

2 数据结构,使用struct,便于数据继承访问,默认全是public;

3 class 完全可以替代struct;

先上代码

#include <iostream>  
#include <unordered_map>  
#include <vector>  
#include <string>  

struct BlockerAttr {
  BlockerAttr() : capacity(10), channel_name("") {}
  explicit BlockerAttr(const std::string& channel)
      : capacity(10), channel_name(channel) {}
  BlockerAttr(size_t cap, const std::string& channel)
      : capacity(cap), channel_name(channel) {}
  BlockerAttr(const BlockerAttr& attr)
      : capacity(attr.capacity), channel_name(attr.channel_name) {}

  size_t capacity;
  std::string channel_name;

 private:
    std::string addr;
};

class Blocker : public BlockerAttr {
 public:
  explicit Blocker(){};
  virtual ~Blocker(){};

 private:
  std::string home;
};

int main()
{
    Blocker b;
    BlockerAttr * attr = new BlockerAttr(2, "test channel");
    std::cout << b.capacity << std::endl;
    std::cout << attr->capacity << std::endl;

    delete attr;
}

相关推荐

  1. 【C++】structclass区别

    2024-06-08 08:46:02       20 阅读
  2. C++ class struct 区别

    2024-06-08 08:46:02       10 阅读
  3. C++之structclass区别

    2024-06-08 08:46:02       18 阅读
  4. 【swift】structclass区别

    2024-06-08 08:46:02       22 阅读
  5. struct union 的区别

    2024-06-08 08:46:02       19 阅读
  6. C++ 中的 struct Class

    2024-06-08 08:46:02       19 阅读
  7. spring mvc struts区别是什么?

    2024-06-08 08:46:02       10 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-06-08 08:46:02       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-06-08 08:46:02       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-06-08 08:46:02       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-06-08 08:46:02       18 阅读

热门阅读

  1. Outlook设置邮箱签名

    2024-06-08 08:46:02       9 阅读
  2. 【设计模式之外观模式 -- C++】

    2024-06-08 08:46:02       8 阅读
  3. 速盾:服务器cdn加速超时如何解决?

    2024-06-08 08:46:02       8 阅读
  4. WDF驱动开发-PNP和电源管理(一)

    2024-06-08 08:46:02       11 阅读
  5. xmind父主题快捷键Ctrl+Enter

    2024-06-08 08:46:02       8 阅读
  6. 关于json文件的保存

    2024-06-08 08:46:02       8 阅读