C++结构的函数

Joh*_*ohn 75 c++ struct function

通常我们可以为C++结构定义一个变量,如

struct foo {
  int bar;
};
Run Code Online (Sandbox Code Playgroud)

我们还可以为结构定义函数吗?我们如何使用这些功能?

Luc*_*ore 121

是的,除了默认访问级别(成员方式和继承方式)之外,a struct与a class相同.(以及class与模板一起使用时带来的额外含义)

因此,类支持的每个功能都由结构支持.您将使用与将它们用于类的方法相同的方法.

struct foo {
  int bar;
  foo() : bar(3) {}   //look, a constructor
  int getBar() 
  { 
    return bar; 
  }
};

foo f;
int y = f.getBar(); // y is 3
Run Code Online (Sandbox Code Playgroud)


0x4*_*2D2 33

结构可以像类一样具有功能.唯一的区别是它们默认是公开的:

struct A {
    void f() {}
};
Run Code Online (Sandbox Code Playgroud)

此外,结构也可以有构造函数和析构函数.

struct A {
    A() : x(5) {}
    ~A() {}

    private: int x;
};
Run Code Online (Sandbox Code Playgroud)