程序如下:
class a
{
public:
int GetSize(){return 0;}
};
class b:public a
{
public:
int GetSize(int nOffset){return nOffset+1;}
};
void CT1Dlg::OnButton4()
{
// TODO: Add your control notification handler code here
class b test;
int n=test.GetSize();
};
C:\t1\t1Dlg.cpp(407) : error C2660: 'GetSize' : function does not take 0 parameters
怎么想也想不明白,请高手指点!多谢!
class a
{
public:
int GetSize(){return 0;}
};
class b:public a
{
public:
int GetSize(int nOffset){return nOffset+1;}
};
void CT1Dlg::OnButton4()
{
// TODO: Add your control notification handler code here
class b test;
int n=test.GetSize();
};
C:\t1\t1Dlg.cpp(407) : error C2660: 'GetSize' : function does not take 0 parameters
怎么想也想不明白,请高手指点!多谢!
->
b test
a* pb = dynamic_cast<a*>(&text);
pb->GetSize();
class b test;
int n = ((a&)test).GetSize();
b test;
test.GetSize();
就是在调用 b 的 b::GetSize(int nOffset) 函数。如果想使用基类的 GetSize ,就不在 b 中重载它;或者重新定义一个基类对象
a test_a;
a.GetSize();或者把基类的 GetSize 定义成一个虑函数,或者再用别的方法。
只能
class b test;
int n=test.GetSize(10);正确这不是虚函数的问题,不可能用派生类调用基类的成员函数的道理。
虚函数只不过是是通过基类地址来访问派生类,的动态绑定。你要实现test.GetSize();
就必须在b只重载GetSize();
当然这样的话最好把基类中的Getsize()申明为虚(当然不申也行)。
a* p = new b;
p->GetSize()是调用B的GetSize()
要是不为虚的话,则为A的GetSize()
这个问题好象是:类继承与函数重载不能同时有效,就如上面所说:
"在子类中,若函数重载后,父类的同名函数就不能用了,被屏蔽了"
当然,下面的说法明显不成立:
"在派生类中如果覆盖的不是虚函数的话,则基类中的同名函数被屏蔽,成员函数调用到的只是派生类中的重载版本。thinking in c++有关于这个问题的详细介绍"
因为如果是虚函数的问题,不会体现在编译错误上(不知说的对不对),况且我这个问题一开始时就出现在虚函数上,为了问题的简化,才把"virtual"去了问题产生过程:
1)以前的类a中有一函数int GetSize();已使用过很多次.
2)现建立一个a的子类b,发现如果GetSize()函数应有一个参数,所以加入一成员:
int GetSize(int n);
3)但以前的的用法应是可以的,所以.......解决:
void CT1Dlg::OnButton4()
{
// TODO: Add your control notification handler code here
b test;
int n=test.a::GetSize();
};问题:只是不明白"在子类中,若函数重载后,父类的同名函数就不能用了,被屏蔽了"
C++语法中没有这个"规矩"吧! 如果有,请指出具体地点!
我一开始时怀疑VC,现在想,也许不是吧
说明:在vc6 vc.net 中都出现这一问题
欢迎大家继续讨论!
{
public:
int GetSize(){return 0;}
};
class b:public a
{
public:
long GetSize(int nOffset){return nOffset+1;}
};
void CT1Dlg::OnButton4()
{
// TODO: Add your control notification handler code here
class b test;
int n=test.GetSize();
};
class a
{
public:
void f(void){}
int f(void){} //build error
};2
class a
{
public:
void f(void){}
int f(int){} //ok, right overload
};3
class a
{
public:
void f(void){}
int f(int){}
};class b:public a
{
public:
void f(void){} // import: no overload,no override, hide
};这里就不是重载了,因为不在一个域(关于域的概念自己去看),所以不能构造重载。
这里是 hided。//建议参考一下 《c++ primer》
//