获取对正确定义的友元函数的未定义引用 -_- [duplicate]

Getting undefined reference to a properly defined friend function -_- [duplicate]

提问人:Sp Maurya 提问时间:7/15/2021 更新时间:7/15/2021 访问量:294

问:

所以。。。我很高兴地从事一个项目,然后我将实现一个朋友函数,该函数在生成任意大小的随机数后返回类的对象。在编译时,它显示错误 undefined reference...等等等等

以下是对实际代码/问题的简要模拟......

类声明: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

类定义:随机.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;
}

这是主要的.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

任何帮助将不胜感激......

C++ undefined-reference friend-function

评论

0赞 eerorika 7/15/2021
#define _RANDOM_H该名称是为语言实现保留的。通过定义它,程序的行为将是未定义的。您应该使用另一个标头保护。
0赞 Eljay 7/15/2021
不要使用 C 头文件,请尝试使用 C++ 头文件 。#include <stdint.h>#include <cstdint>
0赞 JaMiT 7/15/2021
“等等等等”——你真的这么不在乎你的问题吗?
0赞 Eljay 7/15/2021
顺便说一句,如果我在 main 中声明生成,那么它就可以工作了。如果在头文件中声明它,它也可以工作。与现在一样,该函数是一个隐藏的好友,无法通过 ADL 访问。
2赞 JaMiT 7/15/2021
这回答了你的问题吗?编译器看不到在类中定义的友元函数 请注意,在该问题中,最小可重现示例是多么简单。只有一个文件,因此没有标头保护作为干扰。

答:

1赞 Abel 7/15/2021 #1

Random.cpp 中没有任何内容告诉它 generate 是 Random 的函数。使用符号

Random Random::generate(const size_t& sz) {
...

否则,它只是另一个全局函数。 此外,公众似乎表示你希望它曝光,所以不应该有友谊的理由。在 Random.h 中,您的意思可能是

static Random generate(const size_t&);

最后,main 中没有任何内容告诉它 generate 是 Random 的静态函数,所以在 main.cpp 中

Random r = Random::generate(10U);

如果它不是静态的,则需要一个 Random 来调用它。更有可能的是,你真的想要一个构造函数而不是生成,但这更像是一个组织的选择。

评论

1赞 Adrian Mole 7/15/2021
OP 不想成为成员函数;它是班级的朋友generate
0赞 Abel 7/15/2021
将 generate 作为全局函数、朋友并完成构造函数的工作,我将让 OP 澄清需求......