What are the differences between struct and class

2019-02-21 07:08发布

This question was already asked in the context of C#/.Net.

Now I'd like to learn the differences between a struct and a class in C++. Please discuss the technical differences as well as reasons for choosing one or the other in OO design.

I'll start with an obvious difference:

  • If you don't specify public: or private:, members of a struct are public by default; members of a class are private by default.

I'm sure there are other differences to be found in the obscure corners of the C++ specification.

29条回答
我命由我不由天
2楼-- · 2019-02-21 07:40

Class is only meaningful in the context of software engineering. In the context of data structures and algorithms, class and struct are not that different. There's no any rule restricted that class's member must be referenced.

When developing large project with tons of people without class, you may finally get complicated coupled code because everybody use whatever functions and data they want. class provides permission controls and inherents to enhance decoupling and reusing codes.

If you read some software engineering principles, you'll find most standards can not be implemented easily without class. for example: http://en.wikipedia.org/wiki/SOLID_%28object-oriented_design%29

BTW, When a struct allocates a crunch of memory and includes several variables, value type variables indicates that values are embbeded in where struct is allocated. In contrast, reference type variable's values are external and reference by a pointer which is also embedded in where struct is allocated.

查看更多
仙女界的扛把子
3楼-- · 2019-02-21 07:40

Classes are Reference types and Structures are Values types.
When I say Classes are reference types,
basically they will contain the address of an instance variables.

For example:

Class MyClass
{
    Public Int DataMember;  //By default, accessibility of class data members 
                            //will be private. So I am making it as Public which 
                            //can be accessed outside of the class.
}

In main method,
I can create an instance of this class using new operator that allocates memory for this class
and stores the base address of that into MyClass type variable(_myClassObject2).

Static Public void Main (string[] arg)
{
    MyClass _myClassObject1 = new MyClass();
    _myClassObject1.DataMember = 10;

    MyClass _myClassObject2 = _myClassObject1;
    _myClassObject2.DataMember=20;
}

In the above program, MyClass _myClassObject2 = _myClassObject1; instruction indicates that both variables of type MyClass

  1. myClassObject1
  2. myClassObject2

and will point to the same memory location.
It basically assigns the same memory location into another variable of same type.

So if any changes that we make in any one of the objects type MyClass will have an effect on another
since both are pointing to the same memory location.

"_myClassObject1.DataMember = 10;" at this line both the object’s data members will contain the value of 10.
"_myClassObject2.DataMember = 20;" at this line both the object’s data member will contains the value of 20.
Eventually, we are accessing datamembers of an object through pointers.

Unlike classes, structures are value types. For example:

Structure MyStructure
{
    Public Int DataMember;  //By default, accessibility of Structure data 
                            //members will be private. So I am making it as 
                            //Public which can be accessed out side of the structure.
}

Static Public void Main (string[] arg)
{
    MyStructure _myStructObject1 = new MyStructure();
    _myStructObject1.DataMember = 10;

    MyStructure _myStructObject2 = _myStructObject1;
    _myStructObject2.DataMember = 20;
}

In the above program,
instantiating the object of MyStructure type using new operator and
storing address into _myStructObject variable of type MyStructure and
assigning value 10 to data member of the structure using "_myStructObject1.DataMember = 10".

In the next line,
I am declaring another variable _myStructObject2 of type MyStructure and assigning _myStructObject1 into that.
Here .NET C# compiler creates another copy of _myStructureObject1 object and
assigns that memory location into MyStructure variable _myStructObject2.

So whatever change we make on _myStructObject1 will never have an effect on another variable _myStructObject2 of type MyStructrue.
That’s why we are saying Structures are value types.

So the immediate Base class for class is Object and immediate Base class for Structure is ValueType which inherits from Object.
Classes will support an Inheritance whereas Structures won’t.

How are we saying that?
And what is the reason behind that?
The answer is Classes.

It can be abstract, sealed, static, and partial and can’t be Private, Protected and protected internal.

查看更多
别忘想泡老子
4楼-- · 2019-02-21 07:42

Here is a good explanation: http://carcino.gen.nz/tech/cpp/struct_vs_class.php

So, one more time: in C++, a struct is identical to a class except that the members of a struct have public visibility by default, but the members of a class have private visibility by default.

查看更多
Evening l夕情丶
5楼-- · 2019-02-21 07:44

The difference between struct and class keywords in C++ is that, when there is no specific specifier on particular composite data type then by default struct or union is the public keywords that merely considers data hiding but class is the private keyword that considers the hiding of program codes or data. Always some programmers use struct for data and class for code sake. For more information contact other sources.

查看更多
迷人小祖宗
6楼-- · 2019-02-21 07:46

You forget the tricky 2nd difference between classes and structs.

Quoth the standard (§11.2.2 in C++98 through C++11):

In absence of an access-specifier for a base class, public is assumed when the derived class is declared struct and private is assumed when the class is declared class.

And just for completeness' sake, the more widely known difference between class and struct is defined in (11.2):

Member 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.

Additional difference: the keyword class can be used to declare template parameters, while the struct keyword cannot be so used.

查看更多
萌系小妹纸
7楼-- · 2019-02-21 07:47

One other thing to note, if you updated a legacy app that had structs to use classes you might run into the following issue:

Old code has structs, code was cleaned up and these changed to classes. A virtual function or two was then added to the new updated class.

When virtual functions are in classes then internally the compiler will add extra pointer to the class data to point to the functions.

How this would break old legacy code is if in the old code somewhere the struct was cleared using memfill to clear it all to zeros, this would stomp the extra pointer data as well.

查看更多
登录 后发表回答