Chương trình mẫu sau in gì? Đó có phải điều bạn mong đợi không? Vì sao?
#include <iostream>
#include <memory>
class Animal {
public:
~Animal() = default;
virtual void eat(int quantity) {
std::cout << "Animal eats " << quantity << '\n';
}
void speak() {
std::cout << "Animal speaks\n";
}
};
class Dog : public Animal {
public:
void eat(unsigned int quantity) {
std::cout << "Dog eats " << quantity << '\n';
}
void speak() {
std::cout << "Dog speaks\n";
}
};
int main() {
Dog dog;
dog.speak();
dog.eat(42u);
std::unique_ptr<Animal> animal = std::make_unique<Dog>();
animal->speak();
animal->eat(42u);
}Xem đáp án và giải thích
Chương trình in lần lượt Dog speaks, Dog eats 42, Animal speaks, rồi Animal eats 42. speak không phải virtual, còn Dog::eat(unsigned) không override Animal::eat(int); thêm override sẽ làm lộ cả hai lỗi ngay khi compile.
Chương trình in lần lượt Dog speaks, Dog eats 42, Animal speaks, rồi Animal eats 42. speak không phải virtual, còn Dog::eat(unsigned) không override Animal::eat(int); thêm override sẽ làm lộ cả hai lỗi ngay khi compile.
Hãy liên hệ trực tiếp kết luận với kiểu, lifetime, ownership, overload resolution hoặc library contract xuất hiện trong câu hỏi. Nếu kết quả phụ thuộc implementation hoặc vi phạm precondition, cần nói rõ thay vì chỉ đoán output.