【发布时间】:2021-07-02 02:33:00
【问题描述】:
我的代码有问题,连我的教授都不知道为什么会这样。
他希望我用using Persontype= struct{}; 定义结构,而不是结构的正常定义。我不明白为什么或有什么区别。
他也不希望我们在 main 中包含 .cpp 文件。
结构的正常定义可以正常工作,但不适用于 this。
错误
In file included from ...\LABOR1TEST\main.cpp:3:
...\LABOR1TEST\test.hpp:12:6: warning: 'void test(const std::vector<<unnamed struct> >&)' used but never defined
void test(std::vector<PersonType> const &_Personen);
^~~~
[100%] Linking CXX executable LABOR1TEST.exe
CMakeFiles\LABOR1TEST.dir/objects.a(main.cpp.obj): In function `main':
.../LABOR1TEST/main.cpp:12: undefined reference to `test(std::vector<._56, std::allocator<._56> > const&)'
collect2.exe: error: ld returned 1 exit status
mingw32-make.exe[3]: *** [CMakeFiles\LABOR1TEST.dir\build.make:120: LABOR1TEST.exe] Error 1
mingw32-make.exe[2]: *** [CMakeFiles\Makefile2:95: CMakeFiles/LABOR1TEST.dir/all] Error 2
mingw32-make.exe[1]: *** [CMakeFiles\Makefile2:102: CMakeFiles/LABOR1TEST.dir/rule] Error 2
mingw32-make.exe: *** [Makefile:137: LABOR1TEST] Error 2
这是我的代码
main.cpp
#include <iostream>
#include <vector>
#include "test.hpp"
int main() {
PersonType p;
p.Name = "Max";
std::vector<PersonType> TEMPVEC;
TEMPVEC.push_back(p);
TEMPVEC.push_back(p);
test (TEMPVEC);
return 0;
}
test.cpp
#include <iostream>
#include <vector>
#include <string>
#include "test.hpp"
void test(std::vector<PersonType> const &_Personen)
{
for (auto const &i : _Personen)
{
std::cout << i.Name << std::endl;
}
}
还有我的 test.hpp
#include <vector>
#include <string>
#ifndef LABOR1TEST_TEST_HPP
#define LABOR1TEST_TEST_HPP
using PersonType = struct {
std::string Name;
};
void test(std::vector<PersonType> const &_Personen);
#endif //LABOR1TEST_TEST_HPP
CMakeLists.txt
cmake_minimum_required(VERSION 3.17)
project(LABOR1TEST)
set(CMAKE_C++_STANDARD 11)
add_executable(LABOR1TEST main.cpp test.cpp test.hpp)
【问题讨论】:
-
你也需要链接
test.cpp。请给你看 CMakeLists.txt -
@yeputons 好的,它在 C++17 [basic.link]/4.3 中表示在 typedef-declaration 中定义的未命名类的行为就像是出于链接目的该类具有 typedef 名称。所以也许 g++ 是从字面上理解这一点,并且只将该段落应用于
typedef而不是using?我怀疑那是语言的意图,可能是在using被添加到语言之前编写的文本并且从未被重新访问过 -
@yeputons [dcl.typedef]/2 明确表示“这样的 typedef-name 具有与 typedef 说明符引入的语义相同的语义。”所以我倾向于称这是一个 g++ 错误,尽管从技术上讲,该标准是有缺陷的,因为它给出了相互矛盾的要求
-
@MommeSherif 祝贺您发现了标准中的缺陷和可能的 g++ 错误。不是每个人都可以说他们已经做到了:)
-
@M.M 看看我发现了什么:stackoverflow.com/questions/48613758/…
标签: c++ struct typedef using anonymous