这个问题已经在c# /. net上下文中提出过了。

现在我想学习c++中结构体和类的区别。请讨论在OO设计中选择一种或另一种的技术差异以及原因。

我将从一个明显的区别开始:

如果没有指定public:或private:,结构体的成员默认为public;默认情况下,类的成员是私有的。

我敢肯定,在c++规范的晦涩角落里还会发现其他不同之处。


当前回答

这里有一个很好的解释:http://carcino.gen.nz/tech/cpp/struct_vs_class.php

所以,再强调一次:在c++中,结构体与类是相同的,除了结构体的成员默认具有公共可见性,而类的成员默认具有私有可见性。

其他回答

结构的成员默认为public,类的成员默认为private。 结构从另一个结构或类的默认继承是公共的。类从其他结构或类的默认继承是私有的。

class A{    
public:    
    int i;      
};

class A2:A{    
};

struct A3:A{    
};


struct abc{    
    int i;
};

struct abc2:abc{    
};

class abc3:abc{
};


int _tmain(int argc, _TCHAR* argv[])
{    
    abc2 objabc;
    objabc.i = 10;

    A3 ob;
    ob.i = 10;

    //A2 obja; //privately inherited
    //obja.i = 10;

    //abc3 obss;
    //obss.i = 10;
}

这是在VS2005上。

引用c++ FAQ,

[7.8] What's the difference between the keywords struct and class? The members and base classes of a struct are public by default, while in class, they default to private. Note: you should make your base classes explicitly public, private, or protected, rather than relying on the defaults. Struct and class are otherwise functionally equivalent. OK, enough of that squeaky clean techno talk. Emotionally, most developers make a strong distinction between a class and a struct. A struct simply feels like an open pile of bits with very little in the way of encapsulation or functionality. A class feels like a living and responsible member of society with intelligent services, a strong encapsulation barrier, and a well defined interface. Since that's the connotation most people already have, you should probably use the struct keyword if you have a class that has very few methods and has public data (such things do exist in well designed systems!), but otherwise you should probably use the class keyword.

你忘记了类和结构之间棘手的第二个区别。

引用标准(§11.2.2在c++ 98到c++ 11):

在没有访问说明符时 对于基类,假定为public 当声明派生类时 Struct和private在类声明为class时被假设。

为了完整起见,更广为人知的class和struct之间的区别定义在(11.2)中:

类定义的类的成员 关键字类private by 违约。定义的类的成员 使用关键字struct或union 默认为public。

另一个区别是:关键字class可以用来声明模板参数,而struct关键字不能这样使用。

综上所述,我们可以得出结论,概念Class比“Structures”更适合代表现实世界中的对象。很大程度上是因为在课堂上使用的面向对象的概念在解释现实场景时非常实用,因此更容易将它们合并到现实中。例如,对于结构体,默认继承是公共的,但如果我们将此规则应用于现实世界,那就太荒谬了。但在类中,默认继承是私有的,这更现实。

无论如何,我需要证明的是类是一个更广泛的,现实世界适用的概念,而结构是一个原始的概念,具有糟糕的内部组织(即使结构遵循面向对象的概念,他们有一个糟糕的含义)

结构和类之间有3个基本区别

第1 -内存是为堆栈内存中的结构保留的(这接近于编程语言),无论堆栈内存中的类是仅为引用保留的,实际内存是在堆内存中保留的。

默认情况下,结构对待公共类是否对待私有类。

第三,不能在结构中重用代码,但在类中我们可以多次重用相同的代码,称为继承