C++ 入门:结构体和类的区别

类的特点:

  1. (class)可以包含很多可以被调用的函数(functions)
  2. 中除非用public修饰,否则它的成员变量和成员方法对外是不可见的
  3. 中有一对特殊的函数,构造函数(constructor)和析构函数(destructor),它们在对象被创建和销毁时会自动调用。而结构体中没有。
  4. 可以使用特殊方法(成员方法)定义处理新数据类型的操作符
  5. 可以被用作定义其它类的基类(继承)
  6. 声明一个新类型的变量(一个类的实例,即一个对象)只需要类名即可,并不需要class关键字

在c++中,结构体和类之间的唯一区别是成员变量和成员方法默认的可访问性。在结构体中,它们是public的; 在class中它们是private的。

英文原版:

How does a C++ class differ from a C struct? There are a few differences. The key ones are:

  • class can also contain functions [called methods].
  • The member variables and methods are hidden from the outside world, unless their declaration follows a public label.
  • There can be a pair of special methods – the constructor and destructor – that are run automatically when an instance of the class [an object] is created and destroyed.
  • Operators to work on the new data type can be defined using special methods [member functions].
  • One class can be used as the basis for the definition of another [inheritance].
  • Declaring a variable of the new type [an instance of the class; an object] requires just the name of the class – the keyword class is not required.

But what about a struct in C++? The last example here gives a clue. The only difference between a struct and class in C++ is the default accessibility of member variables and methods. In a struct they are public; in a class they are private.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值