如何使我的类私有,仍然有访问

C++ How can I make my class private and still have access?

本文关键字:访问 何使 我的      更新时间:2023-10-16

先生您好!,我正在学习c++,我想修改我当前的程序(一个简单的计算器,让用户选择操作,然后要求他输入2个要计算的数字),并使"Math"类私有,但仍然使程序工作。

我的代码如下,任何帮助将不胜感激:)提前感谢!:

    #include <iostream>
    using namespace std;
    class Math{
        public:
            int addition(int x, int y){
            int sum = x + y;
            return sum;
    }
            int subtraction(int x, int y){
            int difference = x - y;
            return difference;
    }
            int multiplication(int x, int y){
            int product = x * y;
            return product;
    }
            float division(float x, float y){
            float quotient = x / y;
            return quotient;
    }
    };
    int main()
    {
        Math mathObject;
        int n,a,b;
        cout << "t[1] Additionnt[2] Subtractionnt[3] Multiplicationnt[4] DivisionnnChoose Operation number: ";
        cin >> n;
        cout << "nnInput first number: "; cin >> a; cout << "nInput second number: "; cin >> b;
        if(n==1){
            cout << "nnThe answer is " << mathObject.Addition(a,b) << endl;
        }
        if(n==2){
            cout << "nnThe answer is " << mathObject.subtraction(a,b) << endl;
        }
        if(n==3){
            cout << "nnThe answer is " << mathObject.multiplication(a,b) << endl;
        }
        if(n==4){
            cout << "nnThe answer is " << mathObject.division(a,b) << endl;
        }
        return 0;
    }

你可以使你的类最"私有"的是把它放在一个匿名命名空间中。

namespace {
class Math{
// ...
};
} // end anon namespace

这允许同一翻译单元中的任何东西访问匿名命名空间中的项,但该命名空间中的符号对其他翻译单元(即源文件)不可用以进行链接。