class Test
{
private :
int i;
public:
Test(int m)
{
i = m;
}
void restart(int k)
{
Test(k);
}
};
但是,编译器 (VS17) 向我发送了一条错误消息,指出“类 Test 不存在默认构造函数”,但我认为我不需要默认构造函数,因为此类中的所有函数都需要一个 int 类型参数。
最佳答案
在
class Test {
// ...
void restart(int k)
{
Test(k);
}
};
语句 Test(k);
声明了一个名为 k
的 Test
类型的变量。此变量 k
是通过调用不存在的默认构造函数来初始化的。
I don't think I need a default constructor since all functions in this class need a int type argument.
这既不是支持也不是反对类
是否有/需要默认构造函数的理由。
如果您想要在 Test::reset()
中设置 Test::i
的值,那么只需这样做:
class Test
{
private:
int i;
public:
Test(int m) : i{ m } // you should use initializer lists instead of
{} // assignments in the constructors body.
void restart(int k) { i = k; }
};
关于c++ - 我什么时候需要默认构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52509566/