结构和阶级之间的差异 [英] Difference between structure and class

查看:64
本文介绍了结构和阶级之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么在c ++中用class替换结构。如果只有结构和类之间的差异是默认的公共和私有标识符,那么为什么要引入类。可以帮我理解这些之间的确切区别吗?提前致谢。



我尝试了什么:



我搜索过我的网站,但每个地方只有公共和私人标识符的区别。

why structure is replaced by class in c++. If only difference between structure and class is default public and private identifier then why class is being introduced. Can any help me understanding the exact difference between these? Thanks in advance.

What I have tried:

I searched my sites but every place only difference of public and private identifier is given.

推荐答案

基本上这是唯一的区别,但重要的是要了解这种区别的含义是什么是。 C ++旨在支持面向对象,这意味着它应该从头开始强调数据隐藏和封装等功能。为此,您希望尽可能多地隐藏在类中,只暴露明确定义的有意义的操作。因此,默认情况下,该类是私有的。但是,C ++也向后兼容C,这意味着它必须能够与C结构交互,而C结构并非设计为面向对象。
Essentially that is the only difference, but it's important to understand what the implications of that distinction is. C++ was designed to support object-orientation which means that it should, from the ground up, emphasise features such as data hiding and encapsulation. To that end, you want to hide as much as possible in a class, only exposing well-defined, meaningful operations. So, the class is private by default. However, C++ also has backwards compatibility with C which means that it has to be able to interact with C structures which were not designed to be object-oriented.


正如我在评论中指出的那样到 AwildaHarrison 的回答, struct s和 class es之间的唯一区别 C ++ 编程语言,是他们的默认访问说明符: struct 默认访问权限是 public ,而 class 一个是 private 。这意味着您可以编写一个具有相同属性的类和结构,例如尝试:

(基本上,正如Pete已经注意到的那样, struct s在 C ++中是多余的



As I pointed out in my comment to AwildaHarrison's answer, the ONLY difference between structs and classes, in C++ programming language, is their default access specifiers: struct default access is public, while class one is private. That means you might write a class and a struct with identical properties, try, for instance:
(basically, as Pete already noted, structs are redundant in C++)

#include <iostream>
using namespace std;

struct A
{
  A(){cout << "A()" << endl; }
  ~A(){cout << "~A()" << endl;}
};

class B
{
public:
  B(){cout << "B()" << endl; }
  ~B(){cout << "~B()" << endl;}
};

int main()
{

  A a;
  B b;

  cout << "sizeof(A) " << sizeof(A) << endl;
  cout << "sizeof(B) " << sizeof(B) << endl;
}


这篇关于结构和阶级之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆