C++基础

1、简单的C++程序

//
//  main.cpp
//  MyFirstC
//
//  Created by xiaofeifei on 2019/1/27.
//  Copyright © 2019 xiaofeifei. All rights reserved.
//
#include <iostream>
using  namespace std;  //use standard name space
int main(int argc, const char * argv[]) {
    // insert code here...
    //cout is standard out
    //<< 左移操作符在C++中进行了功能改造,语言操作符重载
    cout << "Hello, World!"<<endl;
    return 0;
}

2、C++对C的扩展

2.1、面向对象概念

需求:求圆的周长和面积

数据描述:
半径,周长和面积都用实数表示;
数据处理:
1)输入半径r;
2)计算周长=23.1415r;
3)计算面积=3.1415rr;
4)输出半径r,周长和面积;

方法1:用结构化方法(面向过程)实现

#include <iostream>
using  namespace std;  //use standard name space
//DE01-count the girth and area of circle
int main()
{
    double r, girth, area;
    const double PI = 3.1415;
    cout << "input the radius" << endl;
    cin >> r;
    girth = 2*r*PI;
    area = PI * r * r;
    cout << "radius = " << r << endl;
    cout << "girth = " << girth << endl;
    cout << "area = " << area << endl;
    return 0;
}

输出

input the radius
4
radius = 4
girth = 25.132
area = 50.264
Program ended with exit code: 0

方法2:用面向对象方法实现

#include <iostream>
using  namespace std;  //use standard name space
//DE02-count the girth and are of circle
//面向对象的实现方法
//Circle类的抽象和封装
class Circle
{
public:
    double r;
    double girth;
    double area;
public:
    void setR(double rr)
    {
        r =rr;
    }
    
    double getR()
    {
        return r;
    }
    
    double getGirth()
    {
        return 2*r*3.1415;
    }
    
    double getArea()
    {
        return 3.1415*r*r;
    }
protected:
private:
};
int main()
{
    Circle circle;
    double r;
    cout << "Please input the radius" << endl;
    cin >> r;
    circle.setR(r);
    cout << "radius = " << circle.getR() << endl;
    cout << "girth = " << circle.getGirth() << endl;
    cout << "area = " << circle.getArea() << endl;
    return 0;
}

输出

Please input the radius
5
radius = 5
girth = 31.415
area = 78.5375
Program ended with exit code: 0

思考:C++编译器是如何处理多个对象以及调用类的成员函数的?可查看链接: 编译器对类对象的处理机制

2.2、类中不写成员函数易犯错场景

参考3.1中Circle类的定义中,如果不定义成员函数,直接在成员函数中求得圆的面积并输出,我们来看一下效果怎样,代码如下:


class Circle
{
public:
        double r;
        double area = 3.1415 * r * r;
};

int main()
{
    Circle c1;
    cout << "Please input the radius of circle" << endl;
    cin >> c1.r;
    cout << "Circle area = " << c1.area << endl;
    return 0;
}

输入圆的半径是5,而得到圆的面积结果是0,这是什么原因呢?

Please input the radius of circle
5
Circle area = 0
Program ended with exit code: 0

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Quexl189

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值