2015-06-08 102 views
-1

我有一个简单的问题,我一直无法找到答案。如何用函数外部的constructior声明一个类C++

如果我有一个构造函数的类,例如,

class Test 
{ 
public: 
    Test(int var); 
    ~Test(); 
}; 

,我想声明它的主要外,作为一个静态全局

例如。

static Test test1; 

int main() 
{ 
    return 0; 
} 

我会得到一个错误:如果我尝试使用 static Test test1(50); 我会得到错误 no matching function for call to 'Test::Test()'

:未定义参考

什么是做到这一点的正确方法?我是否需要2个构造函数,一个是空的,另一个是变量?

感谢,

+1

它试图调用默认的构造函数,它确实不存在。您定义了一个接受整数的构造函数,因此您需要将整数传递给构造函数或定义不带参数的构造函数。 – Coda17

+0

在你的程序中,一个不带任何参数的构造函数会有用吗? –

+0

对你更好不知道:'静态测试测试(1);'(请避免它) –

回答

0

最有可能的,你必须为你的类构造函数和析构函数的实现(即使是空的实现),例如:

class Test 
{ 
public: 
    Test() // constructor with no parameters, i.e. default ctor 
    { 
     // Do something 
    } 

    Test(int var) 
    // or maybe better: 
    // 
    // explicit Test(int var) 
    { 
     // Do something for initialization ... 
    } 

    // BTW: You may want to make the constructor with one int parameter 
    // explicit, to avoid automatic implicit conversions from ints. 

    ~Test() 
    { 
     // Do something for cleanup ... 
    } 
};