一个header文件可以配合main中的代码吗?

Can a header file cooperate with code in main?

我读到 #include header.h 是预处理器(因为 #),这意味着它在编译之前得到处理。 这就是我的代码不能 运行 的原因吗?因为我试图用我的 header(带参数)的函数在 main 中创建一个 if 语句,但它不起作用。

Source.cpp

#include <iostream>
#include "Header.h"
using namespace std;

int main(){
test(46);

if (test() > 30){
    cout << "great";
}
else{
    cout << "It needs to be higher";
}


    system("PAUSE");
    return 0;
}

Header.h

using namespace std;

    int test(int x){
        return x;
    }

这不是问题所在。我怀疑您可能会收到编译器错误消息(或链接器错误),因为您已经使用整数参数声明了 test(int x),然后又不使用参数调用它,例如:test().

我已经修改了您的代码以包含一个整数 result:

int main(){
    int result = test(46); // Save the result of calling the function

    if (result > 30){ // Test the value of the result
        cout << "great";
    }
    else{
        cout << "It needs to be higher";
    }


    system("PAUSE");
    return 0;
}

Header.h 文件中的测试函数采用一个 int 作为 parameter.But 在你的代码中你失去了 it.Pass 一个 int 来测试这样的函数。

if (test(42) > 30)

你会得到输出:很好。