📜  C++中的结构与类

📅  最后修改于: 2021-05-30 18:48:24             🧑  作者: 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 equilalent to class Derived : private Base {}
 
int main()
{
  Derived d;
  d.x = 20; // compiler error becuase inheritance is private
  getchar();
  return 0;
}


CPP
// Program 4
#include 
 
class Base {
public:
    int x;
};
 
struct Derived : Base { }; // is equilalent 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 equilalent to class Derived : private Base {}
 
int main()
{
  Derived d;
  d.x = 20; // compiler error becuase inheritance is private
  getchar();
  return 0;
}

CPP

// Program 4
#include 
 
class Base {
public:
    int x;
};
 
struct Derived : Base { }; // is equilalent to struct Derived : public Base {}
 
int main()
{
  Derived d;
  d.x = 20; // works fine because inheritance is public
  getchar();
  return 0;
}
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”