【发布时间】: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 和其他类声明和定义在同一个地方的有很大不同。