虚函数,不解

对继承及虚函数还不是很了解,先记下来。

#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是一样的。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值