C ++如何将我的类设为私有且仍具有访问权限?

时间:2014-05-07 03:37:18

标签: c++ private public

天啊先生! 我只是在学习C ++而我想修改我当前的程序(一个简单的计算器让用户选择操作,然后让他输入2个数字进行计算。)并制作课程'数学&#39 ;私人,但仍然使程序工作。

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

    #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] Addition\n\t[2] Subtraction\n\t[3] Multiplication\n\t[4] Division\n\nChoose Operation number: ";
        cin >> n;
        cout << "\n\nInput first number: "; cin >> a; cout << "\nInput second number: "; cin >> b;

        if(n==1){
            cout << "\n\nThe answer is " << mathObject.Addition(a,b) << endl;
        }

        if(n==2){
            cout << "\n\nThe answer is " << mathObject.subtraction(a,b) << endl;
        }

        if(n==3){
            cout << "\n\nThe answer is " << mathObject.multiplication(a,b) << endl;
        }
        if(n==4){
            cout << "\n\nThe answer is " << mathObject.division(a,b) << endl;
        }
        return 0;
    }

1 个答案:

答案 0 :(得分:2)

关于最多&#34;私人&#34;你可以让你的课成为anonymous namespace

namespace {

class Math{
// ...
};

} // end anon namespace

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