对继承及虚函数还不是很了解,先记下来。
#include <iostream>
using namespace std;
class Base {
public:
Base() {}
Base(const Base &obj) {
cout << "基类复制构造函数" << endl;
}
void Foobar() {
cout << "1" << endl;
}
virtual void Foo() {
cout << "基类" << endl;
}
};
class Derived : public Base {
public:
Derived() {}
void Foobar() {
cout << "2" << endl;
}
void Foo(int a = 0) {
cout << "派生类" << endl;
}
};
int main(int argc, char **argv)
{
Base *p = NULL;
p->Foobar(); // 1
// Java运行时可能会给出空引用,C++运行正常,不解
Derived son;
Base *father = &son;
father->Foobar(); // 1
// 基类和派生类的Foobar是什么关系?
son.Foo(); // 派生类
((Derived *)father)->Foo(); // 派生类
father->Foo(); // 基类
// Derived继承了Base::Foo,但只能通过指向Derived对象的指针或引用来访问Base::Foo,很奇怪
Base(son).Foo(); // 基类复制构造函数 基类
((Base)son).Foo(); // 基类复制构造函数 基类
// 上面两种“强制类型转换”功能一样,都会产生临时的基类对象
return 0;
}
其中有这句
father->Foo(); // 基类
Derived继承了Base::Foo,但只能通过
指向Derived对象的指针或引用来访问Base::Foo,用Derived相关的东西访问Foo则是Derived自己的,很奇怪。
是不是函数默认参数带来的麻烦?
2013/2/25
以下摘自http://t.jobdu.com/redirect.php?goto=findpost&ptid=1721&pid=21283&fromuid=170343
以下不属于重载:
class A{
void f(int,int);
}
class B:A{
void f(float, float);
}
而是类A和类B属于不同的scope,或者有点类似namespace的概念,二者不是一个域中的内容,只是名字相同而已,很多同学把这个当成了重载。
因为重载应该是同一个scope中的,如果要在B中实现重载,应该改成下面这样:
class B:A{
using A::f;
void f(float, float);
}
这里的using和using std:cout是一样的。