面向对象编程(Object-Oriented Programming, OOP)是一种编程范式,它使用"对象"的概念来设计应用程序和计算机程序。C++是一种支持OOP的多范式编程语言。
C++ OOP的四大基本特性:
class Car { // 类定义
private:
string brand; // 私有成员
int year;
public:
// 构造函数
Car(string b, int y) : brand(b), year(y) {}
// 成员函数
void displayInfo() {
cout << "Brand: " << brand << ", Year: " << year << endl;
}
// setter/getter
void setBrand(string b) { brand = b; }
string getBrand() { return brand; }
};
int main() {
Car myCar("Toyota", 2020); // 创建对象
myCar.displayInfo();
return 0;
}
class Vehicle { // 基类
public:
void start() { cout << "Vehicle started" << endl; }
};
class Car : public Vehicle { // 派生类
public:
void drive() { cout << "Car is driving" << endl; }
};
int main() {
Car myCar;
myCar.start(); // 继承自Vehicle
myCar.drive();
return 0;
}
class Shape {
public:
virtual void draw() { cout << "Drawing a shape" << endl; } // 虚函数
};
class Circle : public Shape {
public:
void draw() override { cout << "Drawing a circle" << endl; } // 重写
};
int main() {
Shape* shape = new Circle();
shape->draw(); // 输出"Drawing a circle" - 运行时多态
delete shape;
return 0;
}
问题:当派生类对象赋值给基类对象时,派生类特有部分会被"切掉"
class Base { /*...*/ };
class Derived : public Base { /*...*/ };
Derived d;
Base b = d; // 对象切片发生
解决方案:
问题:当通过基类指针删除派生类对象时,如果基类析构函数不是虚函数,会导致派生类析构函数不被调用
class Base {
public:
~Base() { cout << "Base destructor" << endl; } // 非虚析构函数
};
class Derived : public Base {
public:
~Derived() { cout << "Derived destructor" << endl; }
};
int main() {
Base* b = new Derived();
delete b; // 只调用Base的析构函数
return 0;
}
解决方案:
virtual ~Base() { ... }
问题:多重继承可能导致同一个基类被继承多次
class A { public: int data; };
class B : public A {};
class C : public A {};
class D : public B, public C {}; // D中有两份A的副本
int main() {
D d;
// d.data = 10; // 歧义,不知道是B::data还是C::data
return 0;
}
解决方案:
class B : virtual public A {};
class C : virtual public A {};
class D : public B, public C {}; // 现在D中只有一份A的副本
C++ OOP提供了强大的工具来构建复杂、可维护的软件系统,但也需要开发者深入理解其原理以避免常见陷阱。
没有搜到相关的文章