注册 登录
编程论坛 C++教室

關于繼承的問題

iwar 发布于 2007-05-22 17:37, 389 次点击

各位:以下代碼何錯之有啊??
爲什麽老提示錯誤???


#include<iostream>
class base
{
int m1() { return 30; }
public:
virtual int m2() { return 40; }
virtual ~base() { }
};

class derived : public base
{
public:
int m2() { return 50; }
};

void main()
{
base *p_b = new base();
derived *p_d = new derived();

cout << "b->m3(): " << b->m3() << endl;
cout << "d->m3(): " << d->m3() << endl;
delete b;
b =d;
cout << "b_d->m3(): " << b->m3() <<endl;
delete d;
}

THX!!!!

3 回复
#2
aipb20072007-05-22 17:42
还没看你怎么写的,我想问问:

b,d,m3()这些似乎都没声明!
#3
kisscjy2007-05-23 00:08

错误真不是一般的多
以下打红字的就是你的错误了~~~

#include<iostream>
using namespace std; //少了名字空间
class base
{
int m1() { return 30; }
public:
virtual int m3() { return 40; } //你定义m2,却在主函数中使用了m3
virtual ~base() { }
};

class derived : public base
{
public:
int m3() { return 50; } //同上
};

void main()
{
base *p_b = new base(); //定义指针名称为 p_b,但在主函数中使用了 b;
derived *p_d = new derived(); //同上

cout << "b->m3(): " << p_b->m3() << endl;
cout << "d->m3(): " << p_d->m3() << endl;
delete p_b;
p_b =p_d;
cout << "b_d->m3(): " << p_b->m3() <<endl;
delete p_d;
}

#4
iwar2007-05-23 12:41
原來....
3Q拉!!!!!!!
1