无法访问专用函数


//**** 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);
};

最新更新