C++如何使用结构体与类?代码示例

2021年3月28日12:21:19 发表评论 619 次浏览

在C++中, 结构体与类相同, 但有一些区别。其中最重要的是安全性。结构体不是安全的, 并且在类是安全的并且不能隐藏其编程和设计细节的同时, 不能向最终用户隐藏其实现细节。以下是对此差异进行阐述的要点:

1)默认情况下, 类的成员是私有的, 而结构体的成员是公共的。

例如, 程序1编译失败, 程序2运行正常。

// Program 1
#include <stdio.h>
  
class Test {
     int x; // x is private
};
int main()
{
   Test t;
   t.x = 20; // compiler error because x is private
   getchar ();
   return 0;
}
// Program 2
#include <stdio.h>
  
struct Test {
     int x; // x is public
};
int main()
{
   Test t;
   t.x = 20; // works fine because x is public
   getchar ();
   return 0;
}

2)从类/结构体派生结构体时, 基类/结构体的默认访问说明符是公共的。当派生一个类时, 默认的访问说明符是私有的。

例如, 程序3编译失败, 程序4运行正常。

// Program 3
#include <stdio.h>
  
class Base {
public :
     int x;
};
  
class Derived : Base { }; // is equilalent to class Derived : private Base {}
  
int main()
{
   Derived d;
   d.x = 20; // compiler error becuase inheritance is private
   getchar ();
   return 0;
}
// Program 4
#include <stdio.h>
  
class Base {
public :
     int x;
};
  
struct Derived : Base { }; // is equilalent to struct Derived : public Base {}
  
int main()
{
   Derived d;
   d.x = 20; // works fine becuase inheritance is public
   getchar ();
   return 0;
}

相关文章: C结构体和C++结构体之间的区别

如果发现任何不正确的地方, 或者想分享有关上述主题的更多信息, 请写评论。

被认为是行业中最受欢迎的技能之一, 我们拥有自己的编码基础C ++ STL通过激烈的问题解决过程来训练和掌握这些概念。

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: