📜  C++ 中的结构与类

📅  最后修改于: 2021-09-13 03:13:50             🧑  作者: Mango

在 C++ 中,结构与类相同,但有一些不同。其中最重要的是安全性。结构不安全,无法向最终用户隐藏其实现细节,而类是安全的,可以隐藏其编程和设计细节。以下是阐述这种差异的要点:
1) 类的成员默认是私有的,结构的成员默认是公有的。
例如程序 1 编译失败,程序 2 工作正常。

CPP
// Program 1
#include 
 
class Test {
    int x; // x is private
};
int main()
{
  Test t;
  t.x = 20; // compiler error because x is private
  getchar();
  return 0;
}


CPP
// Program 2
#include 
 
struct Test {
    int x; // x is public
};
int main()
{
  Test t;
  t.x = 20; // works fine because x is public
  getchar();
  return 0;
}


CPP
// Program 3
#include 
 
class Base {
public:
    int x;
};
 
class Derived : Base { }; // is equivalent to class Derived : private Base {}
 
int main()
{
  Derived d;
  d.x = 20; // compiler error because inheritance is private
  getchar();
  return 0;
}


CPP
// Program 4
#include 
 
class Base {
public:
    int x;
};
 
struct Derived : Base { }; // is equivalent to struct Derived : public Base {}
 
int main()
{
  Derived d;
  d.x = 20; // works fine because inheritance is public
  getchar();
  return 0;
}


CPP

// Program 2
#include 
 
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 运行正常。

CPP

// Program 3
#include 
 
class Base {
public:
    int x;
};
 
class Derived : Base { }; // is equivalent to class Derived : private Base {}
 
int main()
{
  Derived d;
  d.x = 20; // compiler error because inheritance is private
  getchar();
  return 0;
}

CPP

// Program 4
#include 
 
class Base {
public:
    int x;
};
 
struct Derived : Base { }; // is equivalent to struct Derived : public Base {}
 
int main()
{
  Derived d;
  d.x = 20; // works fine because inheritance is public
  getchar();
  return 0;
}

3) 类可以有空值,但结构不能有空值。

4)结构的内存分配在堆栈中,而类的内存分配在堆中。

5) 类需要构造函数和析构函数,但结构不需要。

6) 类支持多态,也可以继承,但结构不能继承。

想要从精选的视频和练习题中学习,请查看C++ 基础课程,从基础到高级 C++ 和C++ STL 课程,了解基础加 STL。要完成从学习语言到 DS Algo 等的准备工作,请参阅完整的面试准备课程