【问题标题】:C++: Calling private function in a class from the public section of that classC ++:从该类的公共部分调用该类中的私有函数
【发布时间】:2013-04-03 11:37:11
【问题描述】:

如果我要创建一个类并将多个函数放入私有部分,我将如何从同一个类的公共部分调用这些函数? 示例:

class calculator{
public: //What would go here

private:
    float calculate(float x, char y, float z){
        float answer;

        switch (y){

          case '+':
            answer = x + z;
            break;

          case '-':
            answer = x - z;
            break;

          case '/':
            answer = x / z;
            break;

          case '*':
            answer = x * z;
            break;

          default:
            return(0);
        }
        cout <<"= "; return answer;
    }

    void main(){
        float num1;
        float num2;
        char aOp;
        system("CLS");
        cout << ">> "; cin >> num1 >> aOp >> num2;
        cout << calculate(num1, aOp, num2) << endl << endl;
    }
};

【问题讨论】:

  • 您的void(!) main() 是您班级的private 成员函数(!)?
  • main 可以是 void 类型
  • @cf16 如果它是符合标准的 main 函数,则不是。
  • 他没有说是any_type_main函数,他问怎么调用函数
  • @juanchopanza Main() 在这个例子中是一个错误,只是为了帮助说明我的问题。对困惑感到抱歉。顺便谢谢你的回答。

标签: c++ class function


【解决方案1】:

您只需从公共成员函数中调用私有成员函数:

class Foo
{
 public:
  void foo() { privateFoo(); }
 private:
  void privateFoo();

};

【讨论】:

    【解决方案2】:

    通常就像你现在做的那样。你在同一个班级,所以你可以访问私有方法。 只是主要公开。另请注意,main 不是成员函数的好名称。 main 通常是为程序的入口点保留的,不能在一个类中。

    【讨论】:

      【解决方案3】:

      如果你想调用私有声明的函数,并且如果你想从任何地方调用它,你必须在公共部分调用一个函数(或为继承的类受保护),然后你必须调用它私有函数。

      【讨论】:

        【解决方案4】:

        好的。记住一件事。 私有函数只能在属于同一类成员的另一个函数的帮助下调用。即使是对象也不能使用点运算符调用私有函数。参见这个例子:

        #include<iostream>
        using namespace std;
        class student
        {
        private:
        int m;
        void read void //Private function of the class.
        public:
        void update(void);
        void write(void);
        };
        

        如果 s1 是班级学生的对象,那么我们就不能这样写-

        s1.read(); //it won't work: object can not access private members.
        

        但是我们知道我们可以在同一个类的另一个函数的帮助下调用 read() 函数,所以我们可以在 update() 函数或 write( ) 函数。 所以这里我们在update()函数的帮助下调用read()函数来更新m的值。

        void student :: update(void)
        {
        read(); ///simple call ; no object used
        }
        

        所以,这里是调用私有成员函数的方法。 最后是完整的程序,它在 update() 和 read() 函数的帮助下更新 m 的值。 --

        #include<iostream>
        using namespace std;
        class student
        {
        int m;
        void read()
        {
        m=5;
        cout<<m;
        }
        public:
        void update();
        void write();
        
        };
        void student :: update()
        {
            read();
        }
        int main()
        {
        student s1;
        s1.update();
        return 0;
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-05-27
          • 2016-10-08
          • 2015-04-02
          • 2014-08-06
          • 1970-01-01
          • 2019-09-13
          相关资源
          最近更新 更多