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

发布网友

我来回答

1个回答

热心网友

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

声明声明:本网页内容为用户发布,旨在传播知识,不代表本网认同其观点,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。E-MAIL:11247931@qq.com