CRITICAL SKILL 9.1: Overloading Constructors 构造函数的重载

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.


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{


         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;



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.





>>>>>>>>>>>>>>>>>>>>>>>>translatedby ouyangjun



个人分类: C++basic
想对作者说点什么? 我来说一句