在下面的代码中,我尝试在复合对象中绘制一个圆形对象,但它不会绘制。我不知道为什么。 此代码永远不会达到圆绘制方法。
如果我直接在main.cpp中调用circle的draw()方法,它将绘制..
drawable.h
#pragma once
#include <SFML/Graphics.hpp>
class drawable{
public:
drawable(sf::Vector2f position);
virtual void draw(sf::RenderWindow & window){};
sf::Vector2f position;
};
class circle : public drawable{
public:
circle(sf::Vector2f position);
void draw(sf::RenderWindow & window) override;
};
class composite : public drawable{
public:
composite(sf::Vector2f position, drawable part);
void draw(sf::RenderWindow & window) override;
private:
int count = 0;
drawable part;
};
drawable.cpp
#include "drawable.h"
#include <iostream>
using namespace std;
drawable::drawable(sf::Vector2f position) : position{ position } {
}
circle::circle(sf::Vector2f position) : drawable{ position } {
}
composite::composite(sf::Vector2f position, drawable part) : drawable(position), part{ part }{
}
void circle::draw(sf::RenderWindow & window) {
sf::CircleShape circle;
circle.setPosition(position);
circle.setRadius(30);
window.draw(circle);
}
void composite::draw(sf::RenderWindow & window) {
this->part.position.x = this->position.x + part.position.x;
this->part.position.y = this->position.y + part.position.y;
this->part.draw(window);
}
main.cpp
#include <SFML/Graphics.hpp>
#include "drawable.h"
int main()
{
sf::RenderWindow window = sf::RenderWindow{ sf::VideoMode{ 640, 480 }, "SFML window" };
circle circle{ sf::Vector2f{ 100, 200 } };
composite composite(sf::Vector2f{ 200, 200 }, circle);
window.clear();
composite.draw(window);
window.display();
while (window.isOpen()) {
sf::Event event;
while (window.pollEvent(event)){
if (event.type == sf::Event::Closed){
window.close();
}
}
sf::sleep(sf::milliseconds(20));
}
return 0;
}
答案 0 :(得分:2)
Composite
按值drawable
获取。这意味着在composite
内,您只能获得drawable
个对象;有关混凝土类型的所有信息都将丢失。如果要支持多态对象,则需要使用指针或引用。