【问题标题】:Getting undefined reference to a properly defined friend function -_- [duplicate]获取对正确定义的友元函数的未定义引用-_- [重复]
【发布时间】: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 &lt;stdint.h&gt;,尝试使用C++头文件#include &lt;cstdint&gt;
  • "blah blah blah" -- 你真的关心这个问题吗?
  • 顺便说一句,如果我在 main 中声明 generate ,那么它也可以工作。 如果你在头文件中声明它,它也可以工作。与现在一样,该功能是一个隐藏的朋友,无法通过 ADL 访问。
  • 这能回答你的问题吗? Friend function defined inside class not seen by compiler 注意minimal reproducible example 在那个问题中是多么简单。只有一个文件,因此没有标题保护可以分散注意力。

标签: c++ class undefined-reference friend-function


【解决方案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 来调用它。更有可能你真的想要一个构造函数而不是生成,但这更像是一种组织选择。

【讨论】:

  • OP 不 想要 generate 成为成员函数;它是班级的朋友
  • 用 generate 作为全局函数,一个朋友,做一个构造函数的工作,我会让 OP 澄清想要...
猜你喜欢
  • 2016-09-11
  • 2015-12-30
  • 1970-01-01
  • 2012-05-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多