闽公网安备 35020302035485号
class Animal {
public:
virtual void makeSound() = 0; // 虚函数声明
};
class Cat : public Animal {
public:
void makeSound() override {
cout << "Meow!" << endl;
}
};
class Dog : public Animal {
public:
void makeSound() override {
cout << "Woof!" << endl;
}
};
class Bird : public Animal {
public:
void makeSound() override {
cout << "Chirp!" << endl;
}
};
在这个例子中,Animal 类的 makeSound() 函数被声明为虚函数,这意味着它可以在派生类中被重写。当我们创建一个 Animal 类型的指针或引用时,我们可以指向任何派生类的对象。然后,调用 makeSound() 函数时,实际执行的代码将取决于指向的对象的类型。可维护性: 多态可以提高代码的可维护性,因为它使代码更易于理解和修改。
虚函数: 虚函数是带有 virtual 关键字的成员函数。当调用虚函数时,实际执行的代码将取决于指向的对象的类型。
示例:创建并写入文件
#include <iostream>
#include <fstream>
using namespace std;
int main() {
// 创建 ofstream 对象并打开文件
ofstream myFile("myfile.txt");
// 检查文件是否打开成功
if (myFile.is_open()) {
// 将文本写入文件
myFile << "This is a line of text in my file." << endl;
// 堆代码 duidaima.com
// 关闭文件
myFile.close();
cout << "File written successfully." << endl;
} else {
cout << "Error opening file." << endl;
}
return 0;
}
示例:读取文件#include <iostream>
#include <fstream>
using namespace std;
int main() {
// 创建 ifstream 对象并打开文件
ifstream myFile("myfile.txt");
// 检查文件是否打开成功
if (myFile.is_open()) {
string line;
// 逐行读取文件内容
while (getline(myFile, line)) {
cout << line << endl;
}
// 关闭文件
myFile.close();
} else {
cout << "Error opening file." << endl;
}
return 0;
}
2. 使用 <filesystem> 库#include <iostream>
#include <filesystem>
using namespace std;
namespace fs = std::filesystem;
int main() {
// 创建文件路径
fs::path myFile("myfile.txt");
// 打开文件并写入文本
fs::ofstream ofs(myFile);
if (ofs.is_open()) {
ofs << "This is a line of text in my file." << endl;
ofs.close();
} else {
cout << "Error opening file." << endl;
}
return 0;
}
示例:读取文件#include <iostream>
#include <filesystem>
using namespace std;
namespace fs = std::filesystem;
int main() {
// 创建文件路径
fs::path myFile("myfile.txt");
// 打开文件并读取内容
fs::ifstream ifs(myFile);
if (ifs.is_open()) {
string line;
while (getline(ifs, line)) {
cout << line << endl;
}
ifs.close();
} else {
cout << "Error opening file." << endl;
}
return 0;
}
总结