Function for C++ struct

后端 未结 2 484
无人共我
无人共我 2020-12-12 13:15

Usually we can define a variable for a C++ struct, as in

struct foo {
  int bar;
};

Can we also define functions for a struct? How would we

2条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-12 13:39

    Yes, a struct is identical to a class except for the default access level (member-wise and inheritance-wise). (and the extra meaning class carries when used with a template)

    Every functionality supported by a class is consequently supported by a struct. You'd use methods the same as you'd use them for a class.

    struct foo {
      int bar;
      foo() : bar(3) {}   //look, a constructor
      int getBar() 
      { 
        return bar; 
      }
    };
    
    foo f;
    int y = f.getBar(); // y is 3
    

提交回复
热议问题