即使他是一个学生,也值得尝试回答,因为这是一个复杂的过程,至少对于C ++的新来访者而言并不容易:)
C ++中的类提供两种设计范例的交集,
1)ADT ::基本上是一种新类型,例如整数'int'或实数'double'甚至是诸如'date'的新概念。在这种情况下,简单的类应该看起来像这样,
class NewDataType
{
public:
// public area. visible to the 'user' of the new data type.
.
.
.
private:
// no one can see anything in this area except you.
.
.
.
};
这是ADT的最基本框架...当然,忽略公共区域可能会更简单!并删除访问修饰符(公共的,私有的),整个事情将是私有的。但这只是胡说八道。 因为NewDataType变得无用了!想象一个“ int”,您可以只声明它,但不能执行任何操作。
然后,您需要一些基本不需要NewDataType的有用工具,但是您可以使用它们使您的类型看起来像该语言中的任何“原始”类型。
第一个是构造函数。 语言的很多地方都需要构造函数。看一下int,让我们尝试模仿它的行为。
int x; // default constructor.
int y = 5; // copy constructor from a 'literal' or a 'constant value' in simple wrods.
int z = y; // copy constructor. from anther variable, with or without the sametype.
int n(z); // ALMOST EXACTLY THE SAME AS THE ABOVE ONE, it isredundant for 'primitive' types, but really needed for the NewDataType.
以上各行中的每一行都是一个声明,该变量在此处构造。
最后,想象一个函数中的上述int变量,该函数称为“ fun”,
int fun()
{
int y = 5;
int z = y;
int m(z);
return (m + z + y)
// the magical line.
}
您会看到神奇的一行,在这里您可以告诉编译器您想要的任何东西!完成所有操作后,NewDataType就不再像函数中那样对本地作用域有用,请杀死它。一个经典的例子就是释放“ new”保留的内存!
所以我们非常简单的NewDataType变成了
class NewDataType
{
public:
// public area. visible to the 'user' of the new data type.
NewDataType()
{
myValue = new int;
*myValue = 0;
}
NewDataType(int newValue)
{
myValue = new int;
*myValue = newValue;
}
NewDataType(const NewDataType& newValue){
myValue = new int;
*myValue = newValue.(*myValue);
}
private:
// no one can see anything in this area except you.
int* myValue;
};
现在这是非常基本的框架,要开始构建有用的类,您必须提供公共功能。
在C ++中建立类时,需要考虑很多微型工具,
....
2)对象::基本上是一种新类型,但不同之处在于它属于兄弟,姐妹,祖先和后代。 看看C ++中的'double'和'int','int'是'double'的太阳,因为每个'int'至少在概念上都是'double':)