C++类方法在实际开发中有很多应用案例,以下是一些常见的例子:
class Person {
public:
// 构造函数,用于创建和初始化对象
Person(std::string name, int age) : m_name(name), m_age(age) {}
// 类方法,用于获取对象的信息
static std::string getInfo(const Person& person) {
return "Name: " + person.m_name + ", Age: " + std::to_string(person.m_age);
}
private:
std::string m_name;
int m_age;
};
int main() {
// 使用构造函数创建对象
Person person("Alice", 30);
// 使用类方法获取对象的信息
std::string info = Person::getInfo(person);
std::cout << info << std::endl;
return 0;
}
class Rectangle {
public:
// 构造函数,用于创建和初始化矩形对象
Rectangle(double width, double height) : m_width(width), m_height(height) {}
// 类方法,用于计算矩形的面积
static double getArea(const Rectangle& rectangle) {
return rectangle.m_width * rectangle.m_height;
}
private:
double m_width;
double m_height;
};
int main() {
// 使用构造函数创建矩形对象
Rectangle rectangle(4.0, 5.0);
// 使用类方法计算矩形的面积
double area = Rectangle::getArea(rectangle);
std::cout << "Area: " << area << std::endl;
return 0;
}
#include <fstream>
#include <iostream>
#include <string>
class FileHandler {
public:
// 构造函数,用于打开文件
FileHandler(const std::string& filename, const std::string& mode)
: m_filename(filename), m_file(filename, std::ios::in | std::ios::out) {
if (!m_file.is_open()) {
std::cerr << "Error opening file: " << filename << std::endl;
}
}
// 类方法,用于读取文件内容
static std::string readFile(const std::string& filename) {
FileHandler file(filename, std::ios::in);
if (!file.m_file.is_open()) {
return "";
}
std::string content((std::istreambuf_iterator<char>(file.m_file)),
std::istreambuf_iterator<char>());
return content;
}
// 类方法,用于写入文件内容
static bool writeFile(const std::string& filename, const std::string& content) {
FileHandler file(filename, std::ios::out);
if (!file.m_file.is_open()) {
return false;
}
file.m_file << content;
return true;
}
private:
std::string m_filename;
std::fstream m_file;
};
int main() {
// 读取文件内容
std::string content = FileHandler::readFile("test.txt");
std::cout << "File content: " << content << std::endl;
// 写入文件内容
bool result = FileHandler::writeFile("test.txt", "Hello, World!");
if (result) {
std::cout << "File written successfully." << std::endl;
} else {
std::cerr << "Error writing file." << std::endl;
}
return 0;
}