如何使我的类私有,仍然有访问
C++ How can I make my class private and still have access?
先生您好!,我正在学习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
这允许同一翻译单元中的任何东西访问匿名命名空间中的项,但该命名空间中的符号对其他翻译单元(即源文件)不可用以进行链接。
相关文章:
- 使文件夹中的所有文件可供所有项目(子目录)访问
- 使公共数据成员在C++中无法访问
- 使(虚拟)函数在大多数派生类中无法访问中间基类中可访问,定义良好?
- C++使用其他命名空间中的符号,而不使它们可从外部访问
- 如何使结构内部的可变参数模板可以在外部访问?
- 如何使客户端无法访问命名空间的函数
- 避免使用大量全局变量或使其易于访问和修改的最佳方法
- 使更长的 std::array 可访问,就好像它更短一样
- 如何使对象可以访问上课的其余部分
- 呼叫IASetVerteXbuffers会使以后对设备上下文的所有呼叫造成访问违规(DX 11)
- 如何最好地使网络函数从其他类中访问
- 在类组合中,使包含的类可以访问容器类变量
- 使初始化变量可供多个属性初始化方法访问
- 使用线程控制访问外部API的对象
- 如何使侦听器可以访问C 中的其他功能
- 如何使C 继承保护访问说明器
- 在C++中声明可见性/访问权限的方法有何不同
- C :如何使一组派生的类能够访问一个类的私人成员
- 使查询在 MSADO 的访问中工作
- 使本机代码访问java方法和数据成员