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;
}