当前位置: 动力学知识库 > 问答 > 编程问答 >

class - Can we incorporate member functions inside a structure in C++?

问题描述:

This question already has an answer here:

  • What are the differences between struct and class in C++?

    27 answers

网友答案:

Can we incorporate member functions inside a structure in C++?

Yes. A class is a class, whether it's declared with the class or struct keyword. The only difference is the default accessibility: public for struct, and private for class.

If yes then what is the fun on keeping both Structures and Classes in C++?

A historical oddity. The class keyword was added to make C with Classes (as C++ was originally called) feel more object-orienty; but no-one saw any reason to prevent traditional struct types from behaving just like the new class types, so we've ended up with two more-or-less equivalent words for the same thing.

网友答案:

One obvious answer is that "struct" was included in the standard to give backward compatibility to C.

To allow forward-declared structs in a C interface which underneath is implemented by a C++ class they allowed struct to be a class too with all the features.

In other words, you can publish an interface that can be called from C code:

struct Foo;

#ifdef __cplusplus 
  extern "C" { // to use with C or C++
#endif

void myFunc1( struct Foo * );
int myFunc2( const struct Foo * );

#ifdef __cplusplus 
   }
#endif

Then in your implementation (in C++)

 struct Foo
 {
    private:
       int myMember;
    public:
       void myFunc1();
       int myFunc2() const;
 };

 void myFunc1( Foo * foo ) { foo->myFunc1(); }
 int myFunc2( Foo const* foo ) { return foo->myFunc2(); }

Your class is usable not only from C libraries but C++ libraries that are possibly not binary-compatible with yours (but are with C), from scripting languages that have bindings with C, etc.

分享给朋友:
您可能感兴趣的文章:
随机阅读: