【问题标题】:When do I need a default constructor?什么时候需要默认构造函数?
【发布时间】:2019-03-01 17:59:54
【问题描述】:
class Test
{
private :
    int i;
public:
    Test(int m)
    {
      i = m;
    }
    void restart(int k)
    {
        Test(k);
    }
};

但是,编译器 (VS17) 向我发送了一条错误消息,提示“Test 类不存在默认构造函数”,但我认为我不需要默认构造函数,因为此类中的所有函数都需要 int 类型参数。

【问题讨论】:

  • 请附上minimal reproducible example。该代码不需要默认构造函数,因此问题可能出在其他地方。你想在restart 中做什么?为什么不简单地i = k;
  • 也许您在restart() 中的意图是:Test t(k);
  • @JeremyFriesner 我猜他们试图像普通函数一样“调用构造函数”,希望重新执行构造函数主体中的语句

标签: c++ class oop constructor default


【解决方案1】:

class Test {
// ...
    void restart(int k)
    {
        Test(k);
    }
};

语句Test(k); 声明了一个类型为Test 的变量,名为k。这个变量k是通过调用不存在的默认构造函数来初始化的。

我认为我不需要默认构造函数,因为此类中的所有函数都需要 int 类型参数。

这既不是支持也不是反对 class 拥有/需要默认构造函数的理由。

如果您想要在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; }
};

【讨论】:

  • 能否在类的成员函数中调用类的构造函数来改变该类对象的成员变量值?
  • @CharlieLee 有点像。你可以做*this = Test(k);
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-07-01
  • 2012-12-25
  • 2021-12-12
  • 1970-01-01
  • 1970-01-01
  • 2017-01-10
  • 1970-01-01
相关资源
最近更新 更多