【问题标题】:C++ How can I make my class private and still have access? [closed]C++ 如何使我的课程成为私有的并且仍然可以访问? [关闭]
【发布时间】:2014-06-23 20:50:05
【问题描述】:

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

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

    #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;
    }

【问题讨论】:

  • 将课程设为私有? C++ 没有像 C# 那样在命名空间或二进制模块中私有类的概念。您可以通过将其设置为匿名命名空间来有效地将其在编译单元中设为私有。
  • 主函数中的方法与类中定义的方法不匹配 :L
  • 我怎样才能吃到我的蛋糕呢?没有人知道...呵呵,但说真的,你的程序现在的方式,Math 已经被限制在你定义它的 .cpp 文件中。所以有点私密。如果您想让它“公开”,那么您必须将类声明放在头文件中,并将定义放在 .cpp 文件中。与 C#、Java 和其他类声明和定义在同一个地方的有很大不同。

标签: c++ private public


【解决方案1】:

关于你可以让你的课程最“私密”的方式是将它放入anonymous namespace

namespace {

class Math{
// ...
};

} // end anon namespace

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-20
    • 2012-04-29
    • 2014-08-05
    • 2011-12-11
    • 2021-08-02
    • 2013-07-08
    相关资源
    最近更新 更多