2011年9月26日 星期一

[C++] Constructor call other constructor


#include

class Foo
{
public:
Foo() { Foo(1); };
Foo(int a) { m = a; std::cout <<"Foo " << a << std::endl; }

private:
int m;
};

int main()
{
Foo a, b(2);
return 0;
}

It is ok to call other constructor on method body, but calling other constructor on Initialize list is not allowed!
The following example is not allowed.


#include

class Foo
{
public:
// this will cause compile error!!
Foo() : this(1) { };
Foo(int a) { m = a; std::cout <<"Foo " << a << std::endl; }

private:
int m;
};

int main()
{
Foo a, b(2);
return 0;
}

Reference:
http://stackoverflow.com/questions/308276/c-call-constructor-from-constructor

沒有留言:

張貼留言