#include <iostream>
using namespace std;
int f(int i){cout<<"int f(int i)"<<endl;}
int f(){return 1;}
int main()
{
int f();
f(2);
}
overload_test.cpp: In function ‘int main()’:
overload_test.cpp:8:8: error: too many arguments to function ‘int f()’
f(2);
^
overload_test.cpp:7:9: note: declared here
int f();
第7行的int f() 声明隐藏了外面所有的f
重写虚函数
#include <iostream>
using namespace std;
class Base
{
public:
virtual int f()
{
cout<<"base::f"<<endl;
return 1;
}
};
class Derive: public Base
{
public:
//重写不需要加virtual(当然加了也行) 如果只有返回类型不同既不是重载也不是重写,如void f()报错
int f()
{
cout<<"derive::f"<<endl;
return 1;
}
};
int main()
{
Derive d;
Base* pb=&d;
pb->f();//输出 derive::f
}
类内重载
#include <iostream>
using namespace std;
class Base
{
public:
virtual int f()
{
cout<<"base::f"<<endl;
return 1;
}
};
class Derive: public Base
{
public:
/*int f()
{
cout<<"derive::f"<<endl;
return 1;
}*/
int f(int)
{
cout<<"derive::f_I"<<endl;
return 1;
}
};
class Grand:public Derive
{
};
int main()
{
Derive d;
Base* pb=&d;
Grand g;
// g.f(); //报错,
g.f(2);//输出derive::f_I
//d.f();//报错 被隐藏了
d.f(2);//输出derive::f_I
pb->f();//输出 base::f
//pb->f(2);//报错 因为base并没有定义 int f(int)
}
带有命名空间的