![]() |
|
|
Thread Tools |
|
#1
|
||
|
||
|
Tạo 1 vector chứa abstract class trong c++?
Các anh giúp em với.
Em có 1 abstract class tên là F. có những class khác kế thừa F là A, B, C. Giờ em muốn tạo 1 dạng dữ liệu như này. vector mangF; mangF.push_back(new A); mangF.push_back(new B); mangF.push_back(new C); Có cách nào không ạ? Xin lỗi vì em không biết giải thích như nào cho rõ ràng. |
| thichbuombuom |
| View Public Profile |
| Find all posts by thichbuombuom |
|
#2
|
||
|
||
|
Re: Tạo 1 vector chứa abstract class trong c++?
Em tự làm được rồi. Cảm ơn các anh.
|
| thichbuombuom |
| View Public Profile |
| Find all posts by thichbuombuom |
|
#3
|
||
|
||
|
Re: Tạo 1 vector chứa abstract class trong c++?
|
|
#4
|
||
|
||
|
Re: Tạo 1 vector chứa abstract class trong c++?
Chia sẻ cho anh em đi, tôi cùng có nhu cầu!
__________________
Nguyễn Quang Vinh - o913.o12.o12 VCB: 0031 000 258 001 Website: http://lamhieu.vn |
|
#5
|
|||
|
|||
|
Re: Tạo 1 vector chứa abstract class trong c++?
Code:
class Base
{
public:
virtual void DoSomething() = 0;
};
class DrivedA : public Base
{
public:
void DoSomething() override
{
cout << "test DoA\n";
}
};
class DrivedB : public Base
{
void DoSomething() override
{
cout << "test DoB\n";
}
};
int main()
{
std::vector vecAbstract;
vecAbstract.push_back(new DrivedA);
vecAbstract.push_back(new DrivedB);
for (auto i : vecAbstract)
{
i->DoSomething();
}
for (auto i : vecAbstract)
{
if (i)
{
delete i;
i = nullptr;
}
}
return 0;
}
|
| anhsayvimen |
| View Public Profile |
| Find all posts by anhsayvimen |
|
#6
|
|||
|
|||
|
Re: Tạo 1 vector chứa abstract class trong c++?
Dùng vector chứa con trỏ trỏ tới Base là OK, xong cứ new ra push vào thôi
__________________
Lương Xuân Trường, thi sĩ gãi đít :beauty: https://gph.is/g/ZyPWkMe |
| vothienan1234 |
| View Public Profile |
| Find all posts by vothienan1234 |
![]() |
|
|