类的友元函数产生错误:"未声明'___'成员函数"
Friend Function of Class produces error: "no '___' member function declared"
我有一个类,我正试图创建一个友元函数来操作该类的数据。
下面是我尝试做的一个例子:
// test.hpp
class test
{
public:
friend void friendly_function();
private:
int data;
};
void test::friendly_function()
{
data = 0;
}
然而,编译器抛出了一个错误:test.hpp:23:34: error: no ‘void test::friendly_function()’ member function declared in class ‘test’
我知道我可以用这种方式声明运算符,比如:
class test
{
public:
friend const bool operator<(const test& _lhs, const test& _rhs);
private:
int data;
};
const bool test::operator<(const test& _lhs, const test& _rhs)
{
return (_lhs.data < _rhs.data);
}
那么,为什么我不能用friendly_function
来做这件事呢?友元函数是否只允许作为运算符?
实际上,在发布这个问题之前,我已经解决了这个问题,所以给出答案似乎是明智的,因为其他人可能会发现它在未来很有用。我还将答案设置为"社区维基",这样其他人可以根据自己的意愿进行改进。
问题是友元函数不是类的成员,因此必须在没有test::
说明符的情况下进行编码,因为它们不是class test
的成员。
然而,声明friend void friendly_function();
必须在测试类内部,因为这告诉编译器允许friendly_function()
访问test
的私有成员。
由于friendly_function()
不是class test
的成员,因此最好将所有这些代码放在一个命名空间中,该命名空间将把所有函数和类分组到一个逻辑块中。
namespace test_ns {
class test
{
public:
friend void friendly_function(test &_t);
friend bool operator<(const test& _lhs, const test& _rhs);
private:
int data;
}; // class test
void friendly_function(test &_t)
{
_t.data = 0;
}
bool operator<(const test& _lhs, const test& _rhs)
{
return _lhs.data < _rhs.data;
}
} // namespace test_ns
这应该能解决问题。Friend函数有点微妙,因为它们看起来可能像成员函数,但实际上不是!
相关文章:
- 函数未在作用域中声明 / 如何结合使用 header.h、header.cpp 和 main.cpp?
- 我的函数调用 (C++) 中的未声明标识符
- 未定义与已删除与未声明的函数
- C++ 在 CentOS7 中与 g++ 的 DLL 链接后未声明的函数
- 由于值返回函数中的错误,程序无法编译.它说未声明的标识符
- 为什么 C 允许我调用未声明的函数?
- 'temp'未声明,请先使用此函数
- C 如何从构造函数中声明(错误C2065未宣布的标识符)
- 函数未在此范围内声明
- 尝试使用 std::函数(未定义的符号)声明模板化类状态时出现链接错误
- makefile 和 lex+yacc 中的错误 -> 错误:"noyywrap"未声明(在此函数中首次使用)
- 我们如何有证据表明,声明虚拟函数的类是2个字节,其中一个不超过一个未声明,而在子类中
- 函数参数中未声明和未定义的标识符
- 在此范围错误中未声明函数错误
- 类 'MainWindow' 中未声明任何成员函数
- 错误C2509:成员函数未在派生类中声明
- C++成员函数未声明错误时(当它看起来是错误时)
- 函数未声明(首先使用此函数)
- 函数未声明简单程序
- 无法调用 VBO 实现所需的函数...未声明错误