如何在函数外部声明带有构造函数的类
How to declare a class with a constructior outside of a function C++
我有一个简单的问题,我还没能找到答案。
如果我有一个带有构造函数的类,例如,
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 ... } };
相关文章:
- 我不明白为什么我声明一个空的内部结构并将其传递给构造函数
- 将派生类的构造函数声明为父类的友元
- 用初始化列表和超类构造函数声明子类构造函数的正确方式
- 如何使用构造函数声明指向用户定义对象的指针?
- 如何从构造函数声明新的私有变量?
- 根据二手构造函数声明成员
- 如何用类别的consumetrized构造函数声明使用类的比较对象设置的STL设置
- C++.奇怪的构造函数声明
- 使用ctags查找用c++中的构造函数声明的变量
- 将构造函数声明为private会显示错误.是否至少有一个公共构造函数是必需的
- 如何在C++中使用带参数的构造函数声明具有来自另一个类的类数据的对象
- 在构造函数声明中编写模板类型的参数列表是否有效?
- 在另一个类中使用自定义构造函数声明一个类
- 谷歌测试-构造函数声明错误
- 使用构造函数声明作为虚函数
- 无效地使用不完整的类型模板构造函数声明
- 将构造函数声明为显式时出现编译错误
- 它在构造函数声明中意味着什么
- 类构造函数声明了两次
- 有一种方法可以使用默认的复制构造函数声明复制构造函数非公共和?