This module continues thediscussion of the class begun in Module 8. It examines a number ofclass-related topics, including overloading constructors, passing objects tofunctions, and returning objects. It also describes a special type ofconstructor, called the copy constructor, which is used when a copy of anobject is needed. Next, friend functions are described, followed by structuresand unions, and the ‘this’ keyword. The module concludes with a discussion ofoperator overloading, one of C++’s most exciting features.
>>>>>>这个模块继续讨论在模块8中开始的类。此处会检验许多类相关的主题,包括构造函数的重载、给函数传递对象和对象的返回。还会描述构造函数一种特殊的类型:称为构造函数的拷贝(当在需要拷贝一个对象的时候使用)。在结构体和联合体之后还会有一些函数的讨论,还有”this”关键字。此模块以重载操作的探讨结束(重载是c++的一个令人激动特性)。
CRITICAL SKILL 9.1: Overloading Constructors 构造函数的重载
Although they perform a uniqueservice, constructors are not much different from other types of functions, andthey too can be overloaded. To overload a class’ constructor, simply declarethe various forms it will take. For example, the following program definesthree constructors:
#include <iostream>
using namespace std;
class Sample{
public:
int x;
int y;
//默认的构造函数
Sample(){x = y = 0;}
//带有一个参数的构造函数
Sample(inti){x = y =i;}
//带有两个参数的构造函数
Sample(inti, int j){x = i; y = j;}
};
int main()
{
Sample t; //调用默认的构造函数
Sample t1(5); //使用Sample(int)构造函数
Sample t2(9,10); //使用Sample(int, int)构造函数
cout<<"t.x:"<< t.x <<", t.y:"<< t.y <<"\n";
cout<<"t1.x:"<< t1.x <<", t1.y:"<< t1.y <<"\n";
cout<<"t2.x :"<< t2.x <<", t2.y :"<< t2.y <<"\n";
return 0;
}
Output:
This program creates threeconstructors. The first is a parameterless constructor, which initializes bothx and y to zero. This constructor becomes the default constructor, replacingthe default constructor supplied automatically by C++. The second takes oneparameter, assigning its value to both x and y. The third constructor takes twoparameters, initializing x and y individually.
Overloaded constructors arebeneficial for several reasons. First, they add flexibility to the classes thatyou create, allowing an object to be constructed in a variety of ways. Second,they offer convenience to the user of your class by allowing an object to beconstructed in the most natural way for the given task. Third, by defining botha default constructor and a parameterized constructor, you allow bothinitialized and uninitialized objects to be created.
>>>>>>尽管构造函数的重载是一个独特的服务,事实上构造函数和其他的函数的类型没有什么不同,他们都可以重载。要重载一个类的构造函数,只需声明构造函数(将会发生的构造函数的类型)的各种形式。例如:以下程序定义了三个构造函数:
<<<<<<代码和输出结果如上所示>>>>>>
这个程序创建了三个构造函数。第一个是只带圆括号的构造函数(无参数的构造函数),构造函数初始化参数x=y=0。无参数的构造函数成为了默认的构造函数,取代由c++自动提供的默认的构造函数。第二个是带有一个参数的构造函数,把参数值同时赋值给x和y。第三个构造函数带有两个参数,使用参数单独的初始化x和y。
重载构造函数有几个好处,第一,她给你创建的类增加了灵活性,允许一个对象以各种各样的方式被构建。第二,这样的类给用户提供了便利,为了特定的任务,类的对象可以在更加原始(自然)的方式来构建。第三:定义默认的构造函数和带参数的构造函数,在创建对象的时候给对象初始化或者不初始化。
>>>>>>>>>>>>>>>>>>>>>>>>translatedby ouyangjun
>>>>>>>>>>>>>>>>>>>>>>>>e-mail:ouyangjun1985#msn.com