我有兩個類,一個繼承另一個:
#include <iostream>
#include <vector>
class A
{
public:
int a;
};
class B : public A
{
void print()
{
std::cout << a;
}
};
int main()
{
A* first;
first->a = 5;
std::vector<B*> second;
second.push_back( first ); // the error appears at this line
}
當我嘗試將push_back()typeA*的元素添加到 type 的元素陣列時B*,出現以下錯誤:
no instance of overloaded function "std::vector<_Ty, _Alloc>::push_back [with _Ty=B *, _Alloc=std::allocator<B *>]" matches the argument list
argument types are: (A *)
object type is: std::vector<B *, std::allocator<B *>>
你知道為什么會這樣嗎?
uj5u.com熱心網友回復:
你不能這樣做。
B 是 A 但不是相反。
所以只有當 A 從 B 繼承時它才會起作用。
uj5u.com熱心網友回復:
子類可以解釋為父類的指標,反向不起作用。
正確的一個可能是:
#include <iostream>
#include <vector>
class A
{
public:
int a;
};
class B : public A
{
void print()
{
std::cout << a;
}
};
int main()
{
B* first;
first->a = 5;
std::vector<A*> second;
second.push_back( first );
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/407215.html
標籤:
上一篇:跨DLL邊界的嚴格別名
下一篇:使用指標和我自己的函式反轉字串
