2009年3月20日 星期五

What is a Conversion Constructor

A Conversion constructor is a single-parameter constructor that is declared without the function specifier explicit. The compiler uses converting constructors to convert objects from the type of the first parameter to the type of the converting constructor's class. The following example demonstrates this:

class Y {
int a, b;
char* name;
public:
Y(int i) { };
Y(const char* n, int j = 0) { };
};

void add(Y) { };

int main() {

// equivalent to
// obj1 = Y(2)
Y obj1 = 2;

// equivalent to
// obj2 = Y("somestring",0)
Y obj2 = "somestring";

// equivalent to
// obj1 = Y(10)
obj1 = 10;

// equivalent to
// add(Y(5))
add(5);
}

The above example has the following two converting constructors:

  • Y(int i)which is used to convert integers to objects of class Y.
  • Y(const char* n, int j = 0) which is used to convert pointers to strings to objects of class Y
A copy constructor is a converting constructor.

沒有留言:

張貼留言