gpt4 book ai didi

c++ - 实用函数不会在 .h 文件中初始化并在 main.cpp 中定义

转载 作者:行者123 更新时间:2023-11-30 01:34:29 25 4
gpt4 key购买 nike

我刚刚学习 C++,遇到了 Sublime Text 控制台调试器无法为我解决的问题。我有一个带有两个参数的 stringify 函数,一个是 const auto& arr,一个是 const std::string& ch。我希望能够在我的 main.h 文件中初始化它,我将它导入到我的项目的每个 .cpp 文件中,以便它可用于全局范围。

我已经尝试过正常的方法,只是先在 main.h 中定义它,然后在我的 main.cpp 中填写其余部分

主要.cpp

std::string stringify(const auto& arr, const std::string& ch)
{
std::stringstream ss;
unsigned i = 0;
for (auto& element : arr) {
++i;
// add element to s
ss << element;
// if element isnt the last one.
(i != arr.size()) ? ss << ch : ss;
}
return ss.str();
}

主要.h

#ifndef MAIN_H
#define MAIN_H

#include <iostream>
#include <string>
#include <sstream>
#include <array>
#include <vector>
#include <iterator>
#include <algorithm>

std::string stringify(const auto& arr, const std::string& ch);

#endif // MAIN_H

无论我尝试什么,我都会不断收到“未定义的函数引用”字符串化错误,除非我将完整的函数定义放在 main.h 中。我在这里错过了什么?我一直在阅读文档,但似乎无法弄明白。

最佳答案

注意在函数参数中使用 auto,例如 const auto& arr,目前不是标准 C++。它在 C++20 中有效,但一些编译器已经将其作为扩展实现用于其他 C++ 版本。

不过,它实际上做的是将函数变成一个函数模板,因为现在需要从函数参数中推导出参数的实际类型。所以声明

std::string stringify(const auto& arr, const std::string& ch);

本质上等同于

template <typename T>
std::string stringify(const T& arr, const std::string& ch);

因为你的函数就像一个模板,它的定义需要在头文件中,这样编译器就可以在它与新类型的 arr 一起使用时根据需要实例化它。 (参见 Why can templates only be implemented in the header file?)

关于c++ - 实用函数不会在 .h 文件中初始化并在 main.cpp 中定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56200615/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com