为什么不带参数的构造函数不能用 test(3,5);这种形式调用带参数构造函数 ?
我知道在 C++ 中有个默认参数可以解决这问题,但在 Java 中可以用this(3,5) 来解决,在 C++ 中有没有类似的方法?
#include <iostream>
using namespace std;
class test
{
public:
test()
{
test(3,5);
}
test(int x,int y)
{
this-> x =x;
this-> y =y;
}
void show()
{
cout < <x < < " " < <y < <endl;
}
private:
int x,y;
};
int main()
{
test* one=new test();
one-> show() ;
}
[解决办法]
C++规定不可以。记住C++就是C++,你最好忘了java。
把公共代码抽到另外一个函数里,2个构造函数都调这个函数即可。
[解决办法]
不能. 构造函数不能相互调用.
test()
{
test(3,5);
}
里的test(3,5)产生了一个局部的test对象, 随着括号的结束而消失了.
[解决办法]
test()
{
test(3,5);
}
===>
test()
:x(3), y(5)
{}
[解决办法]
构造函数不可以调用另一个.