包括一个包含头文件的cpp文件

时间:2020-03-25 03:54:36

标签: c++ class constructor compilation header

由于学校工作,我正在尝试学习c ++。最近,我遇到了一个困扰我一段时间的问题。如果有3个文件,则main.cpp,Fish.cpp,Fish.h

Fish.h:

#ifndef FISH_H
#define FISH_H

class Fish
{
    public:
        Fish();
};

#endif

Fish.cpp:

#include <iostream>
#include Fish.h
using namespace std;

Fish::Fish()
{
    cout << "I love fish" << endl;
}

main.cpp:

#include <iostream>
#include "Fish.cpp"
using namespace std;

int main(){
    Fish Salmon;
    return 0;
}

问题来了,我知道是否要在“ main.cpp”中使用Fish()构造函数,应该包含Fish.h,然后编译所有3个文件,但是出于好奇,我试图包含“ Fish.cpp”。如果我在“ main.cpp”中包含“ Fish.cpp”,那么Fish.cpp中的所有内容都将复制到main.cpp中,其中包括行<#include Fish.h>,对吗?但是为什么每次我编译运行时,终端都会给我错误?

1 个答案:

答案 0 :(得分:0)

包括header个文件,不包括cpp个文件。

Fish.cpp

#include <iostream>
#include "Fish.h" // change here
using namespace std;

Fish::Fish()
{
    cout << "I love fish" << endl;
}

main.cpp

#include <iostream>
#include "Fish.h" // change here
using namespace std;

int main(){
    Fish Salmon;
    return 0;
}