The C language struct keyword is retained in C ++ and expanded. In C language, struct can only contain member variables, not member functions. In C ++, struct is similar to class and can contain both member variables and member functions.
struct能包含成员函数吗? 能!
struct能继承吗? 能!!
struct能实现多态吗? 能!!!
#include <iostream>
using namespace std;
struct A
{
public:
A() { cout << "A construct..." << endl;}
virtual ~A(){ cout << "A deconstruct..." << endl;}
};
struct B: public A
{
public:
B() { cout << "B construct..." << endl;}
~B(){ cout << "B deconstruct..." << endl;}
};
int main()
{
A *a = new B();
delete a;
return 0;
}
// A construct...
// B construct...
// B deconstruct...
// A deconstruct...
The struct and class in C ++ are basically universal, only a few details are different:
使用 class 时,类中的成员默认都是 private 属性的;而使用 struct 时,结构体中的成员默认都是 public 属性的。
class 继承默认是 private 继承,而 struct 继承默认是 public 继承。
class 可以使用模板,而 struct 不能。
C ++ did not abandon the struct keyword in the C language, its significance is to give the C language program developers a sense of belonging, and make the C ++ compiler compatible with projects previously developed in the C language.
When writing C ++ code, I strongly recommend using class to define the class and struct to define the structure, which makes the semantics more clear.