如何在函数外部声明带有构造函数的类

How to declare a class with a constructior outside of a function C++

本文关键字:构造函数 声明 函数 外部      更新时间:2023-10-16

我有一个简单的问题,我还没能找到答案。

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

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

,我想在main之外声明它,作为一个静态全局

例如

static Test test1;
int main()
{
    return 0;
}

我会得到一个错误:no matching function for call to 'Test::Test()'

如果我尝试使用static Test test1(50);我将得到错误:Undefined reference

正确的方法是什么?我需要有2个构造函数,一个空的和一个变量?

谢谢,

很可能你必须为你的类构造函数和析构函数提供一个实现(甚至是一个空的实现),例如:

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 ...
  }
};