3

有人可以告诉我为什么在 C++ 中引入了类。是否有一些类可以执行而使用结构无法实现的事情?

4

4 回答 4

1

在这里阅读 Stroustrup 的解释:类有什么了不起的?

类是代码中一个想法、一个概念的表示。类的对象代表代码中思想的特定示例。如果没有类,代码的读者将不得不猜测数据项和函数之间的关系——类使这种关系明确并被编译器“理解”。有了类,程序的高级结构更多地反映在代码中,而不仅仅是注释中。

一个设计良好的类向它的用户展示了一个干净简单的界面,隐藏了它的表示并让它的用户不必知道那个表示。如果表示不应该被隐藏——比如说,因为用户应该能够以任何他们喜欢的方式更改任何数据成员——你可以将该类视为“只是一个普通的旧数据结构”;例如:

struct Pair {
        Pair(const string& n, const string& v) : name(n), value(v) { }
        string name, value;
};

请注意,即使是数据结构也可以受益于辅助函数,例如构造函数。

于 2012-06-14T19:34:12.417 回答
0

Actually, structures in C++ are a special case of classes, and are included to make C++ more backward compatible with C. Recall from C that a structure is a description of a collection of data items of potentially different types that's given a name. This is also somethimes called a record in other languages.

In C++ there is a basic thing called a class, wich is a collection of data items of potentially different types along with functions that operate on them.

In C, a structure lets you define a chunk of memory using the structure declaration as a pattern.

In C++, a class lets you define a chunk of memory using the class declaration as a pattern, and have it associated with functions that operate on it.

In C, a common pattern to do things with a structure is something like this:

struct T {
   ?* some declarations */
};

struct T * foo.

struct T * create_a_T(}{/* malloc memory */}
void init_a_T(struct T * t){/* set it up */}
void do_something_with_T(struct T * t, ?* more arguments*/){/* more good things */}

In C++, a class method works exactly the same way, except that you don't need to have the struct T * as an argument; that's take care of automatically.

Along with all that, in C++ a class lets you make certain elements of the class "private" or "protected", which is to say they're not accessible from outside the class methods. This can protect you from many kinds of programming errors.

Also, in C++ you can use inheritance, which means that you can define a new class that is "just like" an existing class, except for code that adds other data declarations or methods. This lets you organize the code around a relationship called "a kind of", so, for example, you can have a class Car, and define a new class Mercedes that is "a kind of" Car, but has special Mercedes-related pieces.

All of this goes along with the notion of "object oriented programming" which is too much to explain in one answer, but which has historically proven to make it easier to build large programs correctly.

于 2012-06-14T19:45:39.900 回答
0
class CL
{
    int x;
};

struct ST
{
    int x;
};

ST 和 CL 的唯一区别是CL.xisprivateST.xis public

最佳实践:当您定义一个只有公共对象的小型数据结构时,使用关键字 struct,不同地使用关键字 class。

更新:

这是有效的 -->class A;

这是无效的 -->struct B; // error: forward declaration of struct B

于 2012-06-20T12:44:23.810 回答
-7

C++是面向对象的,而对象是由类构成的,所以C++只用它

于 2012-06-14T19:38:01.840 回答