Do I kill a kitten each time I use struct everywhe

2019-04-26 18:30发布

struct is public by default while class is private by default.

Lets take Ogre3D for example; if I change all class occurences with struct, it compiles (I guess), and the engine works just as before.

If I'm right, the compiled code is exactly the same as before, because it's only the compiler that does check if a private/protected methods are called, it's not checked at runtime.

If I'm still right, class is just a keyword that just makes its cute eyes and begging "please encapsulate your data: you'll save a kitten", while private/protected scopes are still up to the user.

I know I sound kinda lame or irrelevantly rebel (something like "C is KISS dude, don't go "

Back to the question: what does the standard say about this little difference between struct and class while generating machine code ? Why add a keyword and try to impress programmers with the so called "OO model" while it's totally not enforced then ? Was it influenced by java ?

标签: c++ class struct
10条回答
看我几分像从前
2楼-- · 2019-04-26 19:03

The only difference between structs and classes in C++ is that classes have private members and base classes by default. Normally changing class to struct shouldn't affect the generated machine code.

查看更多
一夜七次
3楼-- · 2019-04-26 19:05

Hmm, now... If ever you put such a program into public space, say something like OSS, people will throw stones at you ;)

The struct keyword is kind of C heritage. And yes, the only difference (as far as I remember) is the default behaviour regarding members being protected.

Bjarne Stroustrup in "The C++ Programming Language":

By definition, a struct is a class in which members are by default public; that is

struct s { ...

is simply shorthand for

class s { public: ...

But the OO model is by far more than just encapsulation. It adds things like inheritance and member functions.

查看更多
欢心
4楼-- · 2019-04-26 19:06

Actually, class and struct are both checked at compile time. The only difference is whether the default for members who you've not explicitly specified the access for are public (for a struct) or private (for a class). Otherwise, they produce exactly the same objects. If you specify all of your access control explicitly, you can use either one and they will be the same.

查看更多
倾城 Initia
5楼-- · 2019-04-26 19:09

The standard says nothing about generating machine code at all.

struct was retained to make migrating legacy C code easier. Typically, C++ programmers use it for POD-like structures.

查看更多
登录 后发表回答