c++ - 好友功能无法识别

标签 c++ overloading friend-function

我有以下带有几个友元函数的类:

class Teleport
{
public:
    Teleport();
    ~Teleport();
    void display();
    Location teleportFrom(int direction);

    friend bool overlap(Wall * wall, Teleport * teleport);
    friend bool overlap(Location location);
    friend bool overlap(Wall * wall);
    friend bool overlap();

    Location location;
    static vector<Teleport *> teleports;
private:

    int currentTeleport;
};

bool overlapT(vector<Wall *> walls); 

当我像这样将最后一个函数作为友元函数放在类中时:

class Teleport
{
public:
    //...same functions as before...
    friend bool overlapT(vector<Wall *> walls);
    //... same functions as before...
private:
    //... same functions as before...
}

代码在 main.cpp 中产生了一个额外的错误 overlapT was not declared in this scope。至于其他重叠函数(在其他文件中重载),当它们是类中的友元函数时,我会遇到类似的错误:error: no matching function for call to 'overlap()'。我在我认为在另一个文件中以相同的方式使用了友元函数,并且没有编译器错误。是什么导致了这个奇怪的错误?

好的,得到一个小程序来举例说明这个错误!

主要.cpp

#include <iostream>
#include "Teleport.h"

using namespace std;

int main()
{
    Teleport teleport;
    isTrue();
    isNotTrue();
    isTrue(1);
    return 0;
}

传送.h

#ifndef TELEPORT_H
#define TELEPORT_H


class Teleport
{
public:
    Teleport();
    virtual ~Teleport();
    friend bool isTrue();
    friend bool isNotTrue();
private:
    bool veracity;
};

bool isTrue(int a); //useless param, just there to see if anything happens

#endif // TELEPORT_H

传送.cpp

#include "Teleport.h"

//bool Teleport::veracity;

Teleport::Teleport()
{
    veracity = true;
}

Teleport::~Teleport()
{
    //dtor
}

bool isTrue()
{
    return Teleport::veracity;
}

bool isNotTrue()
{
    return !Teleport::veracity;
}

bool isTrue(int a)
{
    if(isTrue())
        return true;
    else
        return isNotTrue();
}

编译错误:

error: too few arguments to function 'bool isTrue(int)'
error: at this point in file
error: 'isNotTrue' was not declared in this scope

我怀疑静态变量可能与此有关,因为我的其他没有静态变量的类工作得很好。

编辑:实际上,静态变量似乎不是问题所在。我刚刚从 Teleport 类定义中删除了 static 关键字/不管它叫什么?,并注释掉了 bool Teleport::veracity;;尽管如此,我仍然遇到两个错误

最佳答案

也许你想要?

class Teleport
{
public:
    Teleport();
    virtual ~Teleport();
    bool isTrue();  // Teleport.isTrue
    bool isNotTrue(); // Teleport.isNotTrue
    friend bool isTrue();
    friend bool isNotTrue();
private:
    static bool veracity;
};

然后

class Teleport
{
public:
    Teleport();
    virtual ~Teleport();
    friend bool isTrue();
    friend bool isNotTrue();
private:
    bool veracity;
};

bool isNotTrue(); // dont forget args
bool isTrue();

关于c++ - 好友功能无法识别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3693781/

相关文章:

c++ - 智能指针和unordered_map,unordered_set等

c++ - 如何将 argv 转换为 CreateProcess 的 lpCommandLine 参数?

c++ - 在试图声明数组的嵌套类中未定义对...的引用?

c++ - 使用用户定义的转换运算符的函数模板重载决议

c++ - 命名空间内的友元函数声明/定义

c++ - Rcpp:将 C++ 函数移植到 R,找不到 'Rcpp.h' 文件

c++ - 重载父类(super class)的函数

c++ - 参数仅相差省略号的函数重载

c++ - 创建友元模板函数时出现意外错误

c++ - 在参数中采用 2 个类的友元函数 - 'Class' 未定义