多态性和文件操作是 C++ 中非常重要的概念之一。多态性使得程序可以根据上下文自动选择正确的函数实现,而文件操作使得程序能够读取、写入和操作文件。让我们深入理解这两个概念。
多态性是面向对象编程中的重要概念,它允许不同的对象对同一消息做出不同的响应。在 C++ 中,多态性通常通过虚函数和继承来实现。
#include <iostream> class Animal { public: virtual void makeSound() { std::cout << "Animal makes a sound" << std::endl; } }; class Dog : public Animal { public: void makeSound() override { std::cout << "Dog barks" << std::endl; } }; class Cat : public Animal { public: void makeSound() override { std::cout << "Cat meows" << std::endl; } }; int main() { Animal* animalPtr; Dog dog; Cat cat; animalPtr = &dog; animalPtr->makeSound(); // 输出: Dog barks animalPtr = &cat; animalPtr->makeSound(); // 输出: Cat meows return 0; }
#include <iostream> class Shape { public: virtual void draw() = 0; // 纯虚函数 }; class Circle : public Shape { public: void draw() override { std::cout << "Circle drawn" << std::endl; } }; class Rectangle : public Shape { public: void draw() override { std::cout << "Rectangle drawn" << std::endl; } }; int main() { Circle circle; Rectangle rectangle; circle.draw(); // 输出: Circle drawn rectangle.draw(); // 输出: Rectangle drawn return 0; }
文件操作是 C++ 中常见的任务之一,它允许程序读取、写入和操作文件。
#include <iostream> #include <fstream> int main() { std::ofstream outFile("example.txt"); if (outFile.is_open()) { outFile << "This is a line of text." << std::endl; outFile << "This is another line of text." << std::endl; outFile.close(); std::cout << "File written successfully." << std::endl; } else { std::cerr << "Unable to open file." << std::endl; } return 0; }
#include <iostream> #include <fstream> #include <string> int main() { std::ifstream inFile("example.txt"); std::string line; if (inFile.is_open()) { while (std::getline(inFile, line)) { std::cout << line << std::endl; } inFile.close(); } else { std::cerr << "Unable to open file." << std::endl; } return 0; }
#include <iostream> #include <fstream> int main() { std::ofstream outFile("example.txt", std::ios_base::app); if (outFile.is_open()) { outFile << "This line is appended to the file." << std::endl; outFile.close(); std::cout << "File appended successfully." << std::endl; } else { std::cerr << "Unable to open file." << std::endl; } return 0; }
多态性和文件操作是 C++ 中重要的概念之一。通过使用虚函数和继承,可以实现多态性,使得程序可以根据上下文选择不同的函数实现。文件操作允许程序读取、写入和操作文件,通过使用输入输出流(ifstream 和 ofstream),可以方便地对文件进行操作。
原文链接:codingdict.net