无法访问私人功能

时间:2012-12-04 10:55:39

标签: c++ private-methods

 //**** Build of configuration Debug for project Calculator ****

   **** Internal Builder is used for build               ****
g++ -O0 -g3 -Wall -c -fmessage-length=0 -o src\Calculator.o ..\src\Calculator.cpp
..\src\/Calculator.h: In function 'std::ostream& operator<<(std::ostream&, CComplex)':
   ..\src\/Calculator.h:38:9: error: 'float CComplex::m_imaginary' is private
  ..\src\Calculator.cpp:79:8: error: within this context
     ..\src\/Calculator.h:37:9: error: 'float CComplex::m_real' is private
   ..\src\Calculator.cpp:81:12: error: within this context
       ..\src\/Calculator.h:38:9: error: 'float CComplex::m_imaginary' is private
        ..\src\Calculator.cpp:81:31: error: within this context
     ..\src\/Calculator.h:37:9: error: 'float CComplex::m_real' is private
       ..\src\Calculator.cpp:85:12: error: within this context
         ..\src\/Calculator.h:38:9: error: 'float CComplex::m_imaginary' is private
       ..\src\Calculator.cpp:85:31: error: within this context
Build error occurred, build is stopped
Time consumed: 687  ms.  

任何人都可以帮助我 - 我正在尝试访问不接受访问权限的私人功能。

2 个答案:

答案 0 :(得分:2)

好吧,如果不是这样,那么这将是一个很好的问题。



  

当在类成员列表之前时,private关键字指定   这些成员只能从成员函数和   班上的朋友。这适用于所有声明的成员   下一个访问说明符或类的结尾。

无法访问成员函数,因为您尝试从类外部访问它。如上所述,private关键字用于防止这种情况。

如果您确实需要从课外访问,那么您需要使用public关键字将其设为公共方法。

在此处查看有关私人关键字的some examples and explanation


看着你的错误,我认为问题在于你的运算符重载&lt;&lt; 。 操作员只能作为朋友功能重载,这本身就可以解决您的问题。

friend std::ostream& operator<<(std::ostream&, CComplex);

答案 1 :(得分:1)

您可能希望成为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);
};
相关问题