c++中vector

来源:百度知道 编辑:UC知道 时间:2024/06/08 01:43:22
#include<iostream>
using std::cout;
using std::endl;
#include<vector>
using std::vector;
class a1
{
public:
a1();
~a1();
virtual void print();
private:
int data;
};
a1::a1()
:data(123)
{
}
void a1::print()
{
cout<<data<<endl;
}
class a2 :public a1
{
public:
a2();
~a2();
virtual void print();
void hello();
};
a2::a2()
{
}
a2::~a2()
{
}
void a2::print()
{
a1::print();
cout<<"now in a2"<<endl;
}
void a2::hello()
{
cout<<"hello world"<<endl;
}
int main()
{
vector<a1*>a1ptr;
a2* a2obj=new a2();
a1ptr.push_back(a2obj);
a1ptr[0]->hello();
return 0;
}

在这个程序里面,我往a1ptr中压入的是派生类a2的指针,为什么在运行的时候还提示
vector.cpp:51: error: ‘class a1’ has n

应该这么说,编译器没你想象中的那么智能。它只确保任何对于a1类,调用hello是语义正确的。而且hello函数不是动态绑定的话,那么调用hello的行为就是在编译期确定的。这样的话无论是不是派生类a2的指针,都只会当成a1的处理。

所以除了你自己提及的两种方法,我认为是没其他办法可以行得通的。

真的觉得每次都要强制转会不爽的话,就定义一个#define一个宏好了。

不用每次强制转换,只需要在定义的时候使用基类指针指向派生类指针即可,比如: a1* a2obj=new a2(); 试试看

你的hello()函数明明是定义在class a2里的嘛,当然class a1中没有啦