Can C++ struct have member functions?

前端 未结 6 1757
孤街浪徒
孤街浪徒 2021-01-30 13:10

I was pretty confused about the difference between struct and class as I seemed to see them used for pretty much the same things. I googled the differences and the only answer I

6条回答
  •  滥情空心
    2021-01-30 14:01

    In the C++98 standard:

    A structure is a class defined with the class-key struct; its members and base classes (clause 10) are public by default (clause 11).

    and

    Members of a class defined with the keyword class are private by default. Members of a class defined with the keywords struct or union are public by default.

    So it means that the only difference between struct and class is the default member access control that is public or private.

    Can C++ struct have member functions?

    Yes, they can.

    My lecturers seem adamant that structs by definition cannot have functions, so what is going on?

    If it is a lecture on C, it is correct. If it is a lecture on C++, it is not correct.

    The only thing I could think of is that maybe the compiler changes functions within a struct to something else so that they technically don't contain functions... Is there a clear answer to these contradictions?

    Yes, there is a clear answer: C++ struct can have member functions.

提交回复
热议问题