#include <iostream>
#include <string>
using namespace std;
class Test
{
private:
static int i;
public:
Test()
{
++i;
}
int getI()
{
return i;
}
~Test()
{
--i;
}
};
int Test::i = 0;
Test t1;
int main()
{
Test t2();
cout << t1.getI() << endl;
Test* p = new Test();
cout << t2.getI() << endl;
delete p;
cout << t2.getI() << endl;
return 0;
}
我在写C++第24课类的静态成员变量这一课的程序时,在这个地方竟然报错
我们一般调用无参构造函数时,是这样写:Test t
我们一般调用有参构造函数时,是这样写:Test t(1)
我写成Test t2()
的理由是调用的是默认参数。
菜鸟老师:Test t2()
声明了一个函数。函数名为 t2,没有参数,返回值是Test类型的。因为没有产生名为 t2 的对象,所以后面使用t2报错
能够以无参形式调用的,都不能加括号,都会被认为是函数声明。无参数对象不能加括号
这个地方是特例,存在二义性,不能加,其它地方如new Test()
和new Test
就都可以。
new Test()
和new Test
是一个意思。