private 和public函数能否重载又如何在类外分别定义?

如题所述

c++中,private和public函数都可以重载。

private和public函数在类外定义的方式是一样的,都是:
返回类型 类名::函数名(参数列表)。

下面是一个例子:
#include <iostream>
using namespace std;
class C
{
public:
int add(int a,int b,int c);
float add(float a,float b);
void sub();
private:
int sub(int a,int b,int c);
float sub(float a,float b);
};
int C::add(int a,int b,int c)
{
return a+b+c;
}
float C::add(float a,float b)
{
return a+b;
}
void C::sub()
{
cout<<"10-1-2="<<sub(10,1,2)<<endl;
cout<<"2.68-1.12="<<sub(2.68,1.12)<<endl;
}
int C::sub(int a,int b,int c)
{
return a-b-c;
}
float C::sub(float a,float b)
{
return a-b;
}
int main()
{
C o;
cout<<"1+2+3="<<o.add(1,2,3)<<endl;
cout<<"2.68+1.12="<<o.add(2.68,1.12)<<endl;
o.sub();
return 0;
}
运行结果如下:
1+2+3=6
2.68+1.12=3.8
10-1-2=7
2.68-1.12=1.56
温馨提示:答案为网友推荐,仅供参考

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网