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

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

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

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

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


当前回答

STRUCT是一种抽象数据类型,它根据结构规范划分给定的内存块。结构体在文件序列化/反序列化中特别有用,因为结构体通常可以被逐字写入文件。(例如,获取一个指向结构的指针,使用SIZE宏计算要复制的字节数,然后将数据移进或移出结构。)

类是一种不同类型的抽象数据类型,试图确保信息隐藏。在内部,可以有各种各样的诡计,方法,临时变量,状态变量。等等,它们都被用来为任何希望使用该类的代码提供一致的API。

实际上,结构体是关于数据的,类是关于代码的。

但是,您确实需要理解这些仅仅是抽象。创建看起来很像类的结构体和看起来很像结构体的类是完全可能的。事实上,最早的c++编译器只是将c++代码转换为C的预编译器。因此,这些抽象有助于逻辑思维,而不一定是计算机本身的资产。

Beyond the fact that each is a different type of abstraction, Classes provide solutions to the C code naming puzzle. Since you can't have more than one function exposed with the same name, developers used to follow a pattern of _(). e.g. mathlibextreme_max(). By grouping APIs into classes, similar functions (here we call them "methods") can be grouped together and protected from the naming of methods in other classes. This allows the programmer to organize his code better and increase code reuse. In theory, at least.

其他回答

STRUCT是一种抽象数据类型,它根据结构规范划分给定的内存块。结构体在文件序列化/反序列化中特别有用,因为结构体通常可以被逐字写入文件。(例如,获取一个指向结构的指针,使用SIZE宏计算要复制的字节数,然后将数据移进或移出结构。)

类是一种不同类型的抽象数据类型,试图确保信息隐藏。在内部,可以有各种各样的诡计,方法,临时变量,状态变量。等等,它们都被用来为任何希望使用该类的代码提供一致的API。

实际上,结构体是关于数据的,类是关于代码的。

但是,您确实需要理解这些仅仅是抽象。创建看起来很像类的结构体和看起来很像结构体的类是完全可能的。事实上,最早的c++编译器只是将c++代码转换为C的预编译器。因此,这些抽象有助于逻辑思维,而不一定是计算机本身的资产。

Beyond the fact that each is a different type of abstraction, Classes provide solutions to the C code naming puzzle. Since you can't have more than one function exposed with the same name, developers used to follow a pattern of _(). e.g. mathlibextreme_max(). By grouping APIs into classes, similar functions (here we call them "methods") can be grouped together and protected from the naming of methods in other classes. This allows the programmer to organize his code better and increase code reuse. In theory, at least.

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

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

另一个主要区别是模板。据我所知,你可以在定义模板时使用类,但不能定义结构。

template<class T> // OK
template<struct T> // ERROR, struct not allowed here

另一件需要注意的事情是,如果你更新了一个有结构的遗留应用程序来使用类,你可能会遇到以下问题:

旧代码有结构,代码被清理,这些被更改为类。 然后将一两个虚函数添加到新更新的类中。

当虚函数在类中时,编译器会在内部添加额外的指针指向类数据,以指向函数。

这将如何打破旧的遗留代码是,如果在旧代码中的某个地方使用memfill将结构清除为零,这也将破坏额外的指针数据。

结构的成员默认为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上。