Làm thế nào để tạo trong C++ một lớp trừu tượng với một số phương thức trừu tượng mà tôi muốn ghi đè trong một lớp con? Giao diện tệp .h
như thế nào? Có .cpp
không, nếu có thì trông như thế nào?C++: Tạo lớp trừu tượng với phương thức trừu tượng và ghi đè phương thức trong lớp con
Trong Java nó sẽ trông như thế này:
abstract class GameObject
{
public abstract void update();
public abstract void paint(Graphics g);
}
class Player extends GameObject
{
@Override
public void update()
{
// ...
}
@Override
public void paint(Graphics g)
{
// ...
}
}
// In my game loop:
List<GameObject> objects = new ArrayList<GameObject>();
for (int i = 0; i < objects.size(); i++)
{
objects.get(i).update();
}
for (int i = 0; i < objects.size(); i++)
{
objects.get(i).paint(g);
}
dịch mã này vào C++ là đủ cho tôi.
Edit:
Tôi tạo ra mã nhưng khi tôi cố gắng để lặp qua các đối tượng tôi nhận được lỗi sau:
Game.cpp:17: error: cannot allocate an object of abstract type ‘GameObject’
GameObject.h:13: note: because the following virtual functions are pure within ‘GameObject’:
GameObject.h:18: note: virtual void GameObject::Update()
GameObject.h:19: note: virtual void GameObject::Render(SDL_Surface*)
Game.cpp:17: error: cannot allocate an object of abstract type ‘GameObject’
GameObject.h:13: note: since type ‘GameObject’ has pure virtual functions
Game.cpp:17: error: cannot declare variable ‘go’ to be of abstract type ‘GameObject’
GameObject.h:13: note: since type ‘GameObject’ has pure virtual functions
Với mã này:
vector<GameObject> gameObjects;
for (int i = 0; i < gameObjects.size(); i++) {
GameObject go = (GameObject) gameObjects.at(i);
go.Update();
}
Mã "trong vòng trò chơi của tôi" ... không đầy đủ, tốt nhất. 'Đối tượng' là gì? Nếu bạn chưa có, tôi khuyên bạn nên lấy một trong những cuốn sách mới bắt đầu từ [Sách hướng dẫn và sách định nghĩa C++ Definitive] (http://stackoverflow.com/questions/388242/the-definitive-c-book-guide -và danh sách). –
Bạn cũng có thể tham khảo bài viết của Herb Sutter, [Virtuality] (http://www.gotw.ca/publications/mill18).htm), thảo luận về nhiều thực tiễn tốt nhất khi sử dụng các hàm ảo và thừa kế trong C++. –