gpt4 book ai didi

c++ - 接口(interface)C++的好处?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:31:23 26 4
gpt4 key购买 nike

看这段代码

#include<iostream>

using namespace std;

//Shape is an Interface Class. No data and everything pure virtual
class Shape {
public:
virtual void Area(int length, int breadth) = 0;
virtual void Perimeter(int length, int breadth) = 0;
//Note, no data
};

//Derived class - Inherits Shape as Public
class Rectangle : public Shape {
public:
void Area(int length, int breadth);
void Perimeter(int length, int breadth);
private:
int someData;
};

//Derived class - Inherits Shape as Public
class Triangle : public Shape {
public:
void Area(int length, int breadth);
void Perimeter(int length, int breadth);
private:
int someData;
};

int main()
{
Rectangle r;
Triangle t;

cout<<"\n\n";
r.Area(3,4);
r.Perimeter(3,4);

t.Area(3,4);
t.Perimeter(3,4);

cout<<"\n\n";
return 0;
}

void Rectangle::Area(int length, int breadth)
{
cout<<"\nThe Area of Rectangle for length = "<<length<<" and\
breadth = "<<breadth<<" is "<<(length * breadth)<<endl;
}

void Rectangle::Perimeter(int length, int breadth)
{
cout<<"\nThe Perimeter of Rectangle for length = "<<length<<" and\
breadth = "<<breadth<<" is "<<2 * (length + breadth)<<endl;
}

void Triangle::Area(int length, int breadth)
{
cout<<"\nThe Area of Triangle for length = "<<length<<" and\
breadth = "<<breadth<<" is "<<(length * breadth)/2<<endl;
}

void Triangle::Perimeter(int length, int breadth)
{
cout<<"\nThe Perimeter of Triangle for length = "<<length<<" and\
breadth = "<<breadth<<" is "<<(length * breadth)/3<<endl;
}

我在代码中使用接口(interface),但我的问题是我应该使用它做什么以及它有什么好处,没有性能,没有真正需要它,为什么我应该使用它(接口(interface))。使用它有什么意义,请您解释一下。

谢谢!

最佳答案

抽象接口(interface)将接口(interface)与实现分开。就像pimpl的成语一样

  • 减少编译时间,并且
  • 让您可以在不破坏 ABI 的情况下更改实现。

两者在大型程序中都是重要的优势。

关于c++ - 接口(interface)C++的好处?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8455961/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com