我什么时候需要默认构造函数?
When do I need a default constructor?
class Test
{
private :
int i;
public:
Test(int m)
{
i = m;
}
void restart(int k)
{
Test(k);
}
};
但是,编译器 (VS17) 向我发送了一个错误,指出 "no default constructor exists for class Test",但我认为我不需要默认构造函数,因为此 class 中的所有函数都需要一个 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.
这既不是支持也不是反对 class
having/needing 默认构造函数的理由。
如果您想要在 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; }
};
class Test
{
private :
int i;
public:
Test(int m)
{
i = m;
}
void restart(int k)
{
Test(k);
}
};
但是,编译器 (VS17) 向我发送了一个错误,指出 "no default constructor exists for class Test",但我认为我不需要默认构造函数,因为此 class 中的所有函数都需要一个 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.
这既不是支持也不是反对 class
having/needing 默认构造函数的理由。
如果您想要在 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; }
};