maf*_*ffo 4 c++ polymorphism virtual inheritance vector
我已经从我的真实代码编辑了这个,所以它更容易理解.
基类:
class MWTypes
{
public:
virtual long get() { return (0); }
};
Run Code Online (Sandbox Code Playgroud)
派生类:(还有其他类,如char,double等等......)
class TypeLong : public MWTypes
{
public:
TypeLong(long& ref) : m_long(ref) {}
~TypeLong();
long get() { return m_long; }
private:
long& m_long;
};
Run Code Online (Sandbox Code Playgroud)
和存储类:
class RowSet
{
public:
void addElememnt(MWTypes elem);
MWTypes getElement();
std::vector<MWTypes> getVector() { return m_row; }
private:
std::vector<MWTypes> m_row;
};
Run Code Online (Sandbox Code Playgroud)
怎么称呼:
for (i = 0; i < NumCols; i++) // NumCols is 3 on this instance
{
switch(CTypeArray[i]) // this is an int which identifies the type
{
case SQL_INTEGER:
{
long _long = 0;
TypeLong longObj(_long);
MWTypes *ptr = &longObj;
// some SQL code goes here that changes the value of _long,
// there is no need to include it, so this will do.
_long++;
// I now want to save the data in a vector to be returned to the user.
rowSet.addElememnt(*ptr);
///////////////////////////////////////////////
// some code happens here that is irrelevant //
///////////////////////////////////////////////
// I now want to return the typr I have saved in the vector,
// I THINK I am doing this right?
MWTypes returned = rowSet.getElement();
// lastly I want to get the value in the returned type
long foo = returned.get();
///////////////////////////////////////////////
// some code happens here that is irrelevant //
///////////////////////////////////////////////
Run Code Online (Sandbox Code Playgroud)
我想我在这里是正确的.'foo'的值始终为0.我感觉这可能是我在向量中存储的方式,或者它可能是基本虚函数,因为它总是返回0.
如果我删除基类中的返回,我会收到LNK2001错误.
MWTypes returned = rowSet.getElement();
// lastly I want to get the value in the returned type
long foo = returned.get();
Run Code Online (Sandbox Code Playgroud)
应该
MWTypes* returned = &rowSet.getElement();
// lastly I want to get the value in the returned type
long foo = returned->get();
Run Code Online (Sandbox Code Playgroud)
要么
MWTypes& returned = rowSet.getElement(); // actually illegal, but MSVC will let you do
// lastly I want to get the value in the returned type
long foo = returned.get();
Run Code Online (Sandbox Code Playgroud)
实际上,必须通过指针或引用进行多态调用.
编辑:这不是你唯一的问题.向量存储对象(而不是指针)的事实将切割对象并破坏其类型信息.
有关其他信息,请参阅此常见问题解答条目,以帮助您解决问题并了解如何调用虚函数.