私有方法实现编译错误

Private method implementation compile error

本文关键字:错误 编译 实现 有方法      更新时间:2023-10-16

我有T类

class T
    {
       public:
       .
       .
       private:
       void foo();
    }
void T::foo()
{
    .. foo body
}

当我尝试编译时,我得到错误:void T::foo()是专用

我应该如何实现私有方法?

私有方法只能在类中使用。

私人、受保护和公共之间的区别?https://isocpp.org/wiki/faq/basics-of-inheritance#access-规则

如果你想在外面使用它,那么你必须公开它。以下是一个关于私人和公共成员的简单示例

#include <iostream>
class T
{
    void bar()
    {
        cout << "Private! Can only be accessed within the class";
    }
    public:
        void foo()
        {
            std::cout << "hello world!"; 
        }
};
int main() {
    // your code goes here
    T testT;
    //testT.bar();      <--uncomment this and you will get the error: 'void T::bar()' is private
    testT.foo();
    return 0;
}

你可能还想了解一下朋友的概念。如果一个函数被声明为T类的友元,它就可以访问私有的foo()。

更多详细信息请点击此处:http://www.cplusplus.com/doc/tutorial/inheritance/