没有输入的默认构造函数

Default constructor with no inputs

本文关键字:默认 构造函数 输入      更新时间:2023-10-16

我试图创建一个没有输入参数的构造函数的类-我试图通过打印到屏幕来测试它。然而,除非我给构造函数一个输入,否则构造函数会直接跳过——调试模式甚至不会将其注册为一行——有人能解释一下吗?

另外,是否有可能从属于不同类的构造函数/函数内部调用另一个类的构造函数?

头文件:

#pragma once
#include <vector>
using namespace std;
class rain
{
public:
    rain(); 
    void update();
    ~rain();
private:
};
源文件:

#include "stdafx.h"
#include "rain.h"
#include "Digital Rain.h"
#include "Stream.h"
#include <Windows.h>
#include <iostream>
#include "Stream.h"

using namespace std;
int screen_width = 79;
rain::rain()
{
    cout << "hi" << endl;
}

void rain::update()
{
    Sleep(5);
}

rain::~rain()
{
}

让我们看一段代码:

#include <iostream>
class rain {
    public:
        rain();
};
rain::rain() {
    std::cout << "hin";
}
int main() {
    rain x();
    rain y;
}

当我们运行这个命令时,我们只会在输出中看到一次hi。这是因为Most Vexing Parse

:

  • x实际上是函数声明,用于不接受参数并返回rain对象的函数。
  • y实际上是rain对象。

此外,您的编译器可能会警告您这种情况。例如,clang将报告:

asdd.cc:26:11: warning: empty parentheses interpreted as a function declaration [-Wvexing-parse]
    rain x();
          ^~
asdd.cc:26:11: note: remove parentheses to declare a variable
    rain x();
          ^~
1 warning generated.