我有以下几个有几个朋友功能的课程:
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()'
。我在朋友函数中使用了我认为在另一个文件中相同的方式,并且没有编译器错误。什么可能导致这个奇怪的错误?
好的,有一个小程序可以说明这个错误!
的main.cpp
#include <iostream>
#include "Teleport.h"
using namespace std;
int main()
{
Teleport teleport;
isTrue();
isNotTrue();
isTrue(1);
return 0;
}
Teleport.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
teleport.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;
;然而,我仍然得到两个错误
答案 0 :(得分:1)
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();