Read-only archive. Login and posting are unavailable.
Reply
 
Thread Tools
  #1  
Old 07-01-2020, 19:26
Đã tốn tiền
Join Date: 03-2015
Posts: 310
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.
Reply With Quote
  #2  
Old 07-01-2020, 20:09
Đã tốn tiền
Join Date: 03-2015
Posts: 310
Re: Tạo 1 vector chứa abstract class trong c++?

Em tự làm được rồi. Cảm ơn các anh.
Reply With Quote
  #3  
Old 01-03-2020, 02:41
Member
Join Date: 03-2013
Posts: 33
Re: Tạo 1 vector chứa abstract class trong c++?

Làm sao đc vậy úp lên đây luôn đi.

Sent from Google Pixel 3 using vozFApp
Reply With Quote
  #4  
Old 02-03-2020, 15:21
Junior Member
Join Date: 04-2011
Posts: 21
Re: Tạo 1 vector chứa abstract class trong c++?

Quote:
Originally Posted by thichbuombuom View Post
Em tự làm được rồi. Cảm ơn các anh.
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
Reply With Quote
  #5  
Old 03-03-2020, 09:27
anhsayvimen's Avatar
Senior Member
Join Date: 02-2012
Posts: 145
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;
}
Lớp trừu tượng sao tạo đc instance nhỉ, ko hiểu thím thớt làm kiểu gì. Dùng con trỏ như trên thì ok.
Reply With Quote
  #6  
Old 05-03-2020, 12:56
vothienan1234's Avatar
Senior Member
Join Date: 09-2016
Posts: 1,110
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
Reply With Quote
Reply

« Previous Thread | Next Thread »

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off


All times are GMT +7. The time now is 17:29.