| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 1620 人关注过本帖
标题:不能理解接口
只看楼主 加入收藏
rohalloway
Rank: 6Rank: 6
等 级:侠之大者
威 望:8
帖 子:97
专家分:405
注 册:2018-9-28
结帖率:75%
收藏
已结贴  问题点数:20 回复次数:3 
不能理解接口
程序代码:
#include <iostream>
#include <string>
using namespace std;

class Shape
{
public:
    virtual int getArea() = 0;

    void setWidth(int w)
    { 
        width = w;
    }

    void setHeight(int h)
    {
        height = h;
    }

protected:
    int width;
    int height;
};

class Rectangle : public Shape
{
public:
    int getArea()
    {
        return (width * height);
    }
};

class Triangle : public Shape
{
public:
    int getArea()
    {
        return (width * height) / 2;
    }
};

int main()
{
    Rectangle Rect;
    Triangle  Tri;

    Rect.setWidth(5);
    Rect.setHeight(7);
    cout << "Total Rectangle area: " << Rect.getArea() << endl;

    Tri.setWidth(5);
    Tri.setHeight(7);
    cout << "Total Triangle area: " << Tri.getArea() << endl;
}


运行结果:
Total Rectangle area: 35
Total Triangle area: 17

------------------------------------------------

问题:

当我在纯虚类中注销掉这句时 //virtual int getArea() = 0;
程序的运行结果也是正确的,那么该如何理解这个接口?
此处的接口倒地起了什么作用呢?

在网上看了一些例子,一直不能理解C++的接口,但又觉得这个功能非常实用,
请教我,谢谢。

[此贴子已经被作者于2019-3-1 02:13编辑过]

搜索更多相关主题的帖子: 接口 class public int return 
2019-03-01 02:06
rjsp
Rank: 20Rank: 20Rank: 20Rank: 20Rank: 20
等 级:版主
威 望:528
帖 子:9007
专家分:53942
注 册:2011-1-18
收藏
得分:20 
假如你以 Shape* 或 Shape& 引用 Rectangle/Triangle 对象,那么有 virtual 修饰时,就调用的是实际对象的 getArea

2019-03-01 08:37
rjsp
Rank: 20Rank: 20Rank: 20Rank: 20Rank: 20
等 级:版主
威 望:528
帖 子:9007
专家分:53942
注 册:2011-1-18
收藏
得分:0 
随便举个例子吧
程序代码:
#include <iostream>
using namespace std;

class Shape
{
public:
    Shape( int w, int h ) : width(w), height(h)
    {
    }
    virtual ~Shape()
    {
    }

    virtual int Area() const = 0;

protected:
    int width;
    int height;
};

class Rectangle : public Shape
{
public:
    using Shape::Shape;
    virtual int Area() const
    {
        return width * height;
    }
};

class Triangle : public Shape
{
public:
    using Shape::Shape;
    virtual int Area() const
    {
        return (width * height) / 2;
    }
};

void Test( const Shape& s )
{
    cout << s.Area() << endl;
}

int main( void )
{
    Rectangle Rect(5,7);
    Triangle  Tri(5,7);

    Test( Rect );
    Test( Tri );
}

如上代码中,Test 函数无须区分参数 s 的类型是 Rectangle 还是 Triangle,简单明了。
2019-03-01 08:50
rohalloway
Rank: 6Rank: 6
等 级:侠之大者
威 望:8
帖 子:97
专家分:405
注 册:2018-9-28
收藏
得分:0 
非常感谢!
2019-03-01 11:14
快速回复:不能理解接口
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.018043 second(s), 9 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved