【发布时间】:2021-09-24 08:06:49
【问题描述】:
所以...我很高兴地在一个项目上工作,然后我打算实现一个朋友函数,它在生成任意大小的随机数后返回该类的一个对象。在编译时,它显示错误 undefined reference... blah blah blah
下面是对实际代码/问题的简要模仿...
类声明:Random.h
// Random Declarations
#ifndef _RANDOM_H
#define _RANDOM_H
#include <stdint.h>
#include <vector>
#include <ostream>
using uv = std::vector<uint16_t>;
using std::ostream;
using std::size_t;
class Random {
uv data;
public:
friend Random generate(const size_t&);
friend ostream& operator<< (ostream&, const Random&);
};
#endif
类定义:Random.cpp
// Random Definitions
#include "Random.h"
#include <cstdlib>
Random generate(const size_t& sz) {
Random newRandom;
newRandom.data.resize(sz);
for(auto &x : newRandom.data) {
x = rand();
}
return newRandom;
}
ostream& operator<< (ostream& out, const Random& random) {
if(random.data.empty()) {
out << '0';
} else {
for(auto &x : random.data) {
out << x;
}
}
return out;
}
这里是main.cpp
#include <iostream>
#include "Random.h"
int main() {
Random r = generate(10U); // <-- This line is throwing the error
std::cout << r << "\n";
}
错误:
PS D:\INT\The Friend Issue> g++ main.cpp Random.cpp
main.cpp: In function 'int main()':
main.cpp:5:28: error: 'generate' was not declared in this scope
Random r = generate(10U);
^
顺便说一句,如果我在 main 中声明生成,那么它也可以工作。
#include <iostream>
#include "Random.h"
Random generate(const std::size_t&);
int main() {
Random r = generate(10U);
std::cout << r << "\n";
}
没有错误
PS D:\INT\The Friend Issue> g++ main.cpp Random.cpp
PS D:\INT\The Friend Issue> .\a.exe
4118467633426500191691572411478293582696224464
任何帮助将不胜感激......
【问题讨论】:
-
#define _RANDOM_H该名称是为语言实现保留的。通过定义它,程序的行为将是未定义的。您应该使用另一个标头保护。 -
不要使用C头文件
#include <stdint.h>,尝试使用C++头文件#include <cstdint>。 -
"blah blah blah" -- 你真的关心这个问题吗?
-
顺便说一句,如果我在 main 中声明 generate ,那么它也可以工作。 如果你在头文件中声明它,它也可以工作。与现在一样,该功能是一个隐藏的朋友,无法通过 ADL 访问。
-
这能回答你的问题吗? Friend function defined inside class not seen by compiler 注意minimal reproducible example 在那个问题中是多么简单。只有一个文件,因此没有标题保护可以分散注意力。
标签: c++ class undefined-reference friend-function