无法访问专用函数
Unable to access a private function
//**** Build of configuration Debug for project Calculator ****
**** Internal Builder is used for build ****
g++ -O0 -g3 -Wall -c -fmessage-length=0 -o srcCalculator.o ..srcCalculator.cpp
..src/Calculator.h: In function 'std::ostream& operator<<(std::ostream&, CComplex)':
..src/Calculator.h:38:9: error: 'float CComplex::m_imaginary' is private
..srcCalculator.cpp:79:8: error: within this context
..src/Calculator.h:37:9: error: 'float CComplex::m_real' is private
..srcCalculator.cpp:81:12: error: within this context
..src/Calculator.h:38:9: error: 'float CComplex::m_imaginary' is private
..srcCalculator.cpp:81:31: error: within this context
..src/Calculator.h:37:9: error: 'float CComplex::m_real' is private
..srcCalculator.cpp:85:12: error: within this context
..src/Calculator.h:38:9: error: 'float CComplex::m_imaginary' is private
..srcCalculator.cpp:85:31: error: within this context
Build error occurred, build is stopped
Time consumed: 687 ms.
有人能帮我吗?我正在尝试访问一个不接受访问的私人功能。
如果不是这样,那么这将是一个很好的问题。
在类成员列表前面时,private关键字指定这些成员只能通过成员功能访问,并且班上的朋友。这适用于在下一个访问说明符或类的末尾。
成员函数不可访问,因为您正试图从类外部访问它。如上所述,private关键字正是用来防止这种情况发生的。
如果确实需要从类外部进行访问,则需要使用public关键字使其成为公共方法。
在这里查看一些关于private关键字的示例和解释。
看看你的错误,我认为问题在于你的运算符重载<lt。运算符只能作为友元函数重载,友元函数本身应该可以解决您的问题。
friend std::ostream& operator<<(std::ostream&, CComplex);
您可能想让operator<<
成为CComplex
类的朋友。类似这样的东西:
class CComplex {
...
// It doesn't matter whether this declaration is on a private,
// public or protected section of the class. The friend function
// will always have access to the private data of the class.
friend std::ostream& operator<<(std::ostream&, CComplex);
};
相关文章:
- 字符串化递归的"std::vector<std::vector<...>>"而不使用部分模板函数专用化
- 使用 C++20 概念模板函数专用化时的依赖项
- 将 c++ 类成员函数专用于模板类
- 使用模板模板参数进行模板定义的函数专用化
- 返回值的简单模板类成员函数专用化
- 已专用类的成员函数专用化
- 部分模板函数专用化enable_if:默认实现
- 使用数组参数进行函数专用化
- 模板函数专用化的内部编译器错误
- 在子类中定义可变参数函数专用化
- 使用模板的构造函数专用化
- 模板函数专用化Enable_if
- 如何将模板构造函数专用化移动到 cpp 文件
- 模板类模板构造函数专用化
- 模板类是否可以用作模板函数专用化的参数
- 未调用数组的函数专用化
- 如何将模板成员函数专用化为另一个模板类
- 模板类的模板函数专用化
- 参数值的自动模板函数专用化
- 如何在类中使用成员函数专用化