C++通过接口给参数赋值
时间: 2023-11-13 09:04:13 浏览: 51
在 C++ 中,可以通过接口给参数赋值。具体来说,接口可以定义一个抽象基类,由该抽象基类派生出具体的类。派生类可以实现抽象基类中定义的纯虚函数,从而实现接口的功能。
在使用接口时,可以将实现了该接口的对象作为参数传递给函数或者方法。例如:
```cpp
class IShape {
public:
virtual double area() const = 0;
};
class Rectangle : public IShape {
public:
Rectangle(double width, double height) : width(width), height(height) {}
double area() const override { return width * height; }
private:
double width, height;
};
void printArea(const IShape& shape) {
std::cout << "Area: " << shape.area() << std::endl;
}
int main() {
Rectangle rect(3.0, 4.0);
printArea(rect);
return 0;
}
```
在上面的例子中,`IShape` 是一个抽象基类,定义了一个纯虚函数 `area()`,表示计算面积的方法。`Rectangle` 类实现了 `IShape` 接口,并重载了 `area()` 方法,计算矩形的面积。`printArea()` 函数接受一个 `IShape` 类型的参数,并调用其 `area()` 方法计算面积并输出。在 `main()` 函数中,创建了一个 `Rectangle` 对象,并将其作为参数传递给 `printArea()` 函数。该函数会调用 `Rectangle::area()` 方法计算面积,并将结果输出。
通过接口给参数赋值可以实现多态,提高代码的灵活性和可扩展性。