c++ - 在 C++ 中为函数和类使用多个文件

标签 c++ function class file-io include

我想弄清楚如何制作一个由单独文件组成的程序。我读了这篇文章:

Function Implementation in Separate File

但是一直没有成功。我有 3 个文件:main.cpp、func.cpp、time.h,当我编译时,我收到此错误消息:

duplicate symbol getOpen(std::basic_ofstream<char, std::char_traits<char> >&)in:
    /var/folders/kp/57zkm0tn1q7b7w0cs7tlf98c0000gn/T//cczaW1Px.o
    /var/folders/kp/57zkm0tn1q7b7w0cs7tlf98c0000gn/T//ccvOCRgc.o
ld: 1 duplicate symbol for architecture x86_64
collect2: ld returned 1 exit status

我不知道这是什么意思。我基本上只是想打开一个文件,写入它,然后关闭它。我也刚刚创建了一个对象并对其进行了测试。我知道问题出在 func.cpp 上,因为当我删除它时它起作用了。有人可以建议吗?谢谢。

我输入这个来编译:g++ main.cpp func.cpp

这是我的代码:

时间.h

#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <fstream>
using namespace std;

class Time
{
    private:
        int seconds;
        int minutes;
        int hours;
    public:
        Time(int=0, int=0, int=0);
        Time(long);
        void showTime();
};

Time::Time(int sec, int min, int hour)
{
    seconds = sec;
    minutes = min;
    hours = hour;
}

Time::Time(long sec)
{
    hours = int(sec / 3600);
    minutes = int((sec % 3600)/60);
    seconds = int( (sec%60) );
}

void Time::showTime()
{
    cout << setfill('0')
         << setw(2) << hours << ':'
         << setw(2) << minutes << ':'
         << setw(2) << seconds << endl;
}

func.cpp

#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;

int getOpen(ofstream& fileOut)
{
    string filename = "outfile.txt";
    fileOut.open(filename.c_str());

    if( fileOut.fail())
    {
        cout << "\nFailed to open file.\n";
        exit(1);
    }
    else
        return 0;
}

main.cpp

#include <iostream>
#include "time.h"
#include "func.cpp"

int main()
{
    ofstream outFile;
    Time t1;

    t1.showTime();

    getOpen(outFile);

    outFile << "This is a test" << endl;

    outFile.close();

    return 0;
}

最佳答案

您将 "func.cpp" 包含到 main.cpp 中,因此您有一个 getOpen 的双重声明。

关于c++ - 在 C++ 中为函数和类使用多个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20228420/

相关文章:

c++ - 嵌套类中的类实例化

c++ - 是否有任何浏览器发送 multipart/form-data 子部分?

javascript - 没有大括号的 JavaScript 中的 Lambda 函数语法

python - 我正在用 python 制作龙与地下城风格的游戏,但如果返回,我会得到不正确的结果

c++ - 在 C++ 中设置 vector

c++ - 通过 CMake 定义预处理器宏?

c++ - 了解指向类型类成员的指针 - 无多态性

ios - 从我的 Apple Watch 启动 iPhone 应用程序的功能?

c - C中是否有一个函数可以接受用户输入并在输入的文件名有效时返回?

C#:帮助理解 UML 类图中的 <<property>>