项目空间

学习笔记N-025

面向对象的思想

更新
内容块
17
阅读
约 2 分钟
路径
学习笔记 / C++

最近发现在我对 c++的学习中,单纯的把 c++用成了“更加高效的 c 语言”而经常没有使用“面向对象的编程语言”

甚至是 c#,我也是完全按照面向过程的思想进行程序设计的

或许得真正自己写一个功能多,跨文件,代码量大的程序。或是隔几个月再阅读自己之前的代码,才可以体会到面向对象和面向过程的区别

现在在竞赛中写面向过程是因为“我能记得住”“我不会搞乱他们”

一个简单的例子,判断长和宽并计算周长和面积

算法很简单,主要是程序设计上的不同;

代码块C++
#include <bits/stdc++.h>
using namespace std;

    double length = 1;
    double width = 1;
    double Perimeter = 0;
    double Area = 0;
    
bool setting(double length,double width){
    if(length<20.0&&length>0.0&&width<20.0&&width>0.0) return true;
     else return false;
        }

double Anthropic1(double length,double width){
Perimeter=length*2 + width*2;
return Perimeter;
}
double Anthropic2(double length,double width){
Area=length * width;
return Area;
}
int main(){
    cin >> length >> width;
    if(!setting(length,width)){
    cout<<"The value you input is not within the required range."<<endl;
    }else{
    printf("the perimeter is %.2f,the area is %.2f.",Anthropic1(length,width),Anthropic2(length,width));
    }
}































代码块C++
#include <iostream>
#include <iomanip>
using namespace std;

class Rectangle {
private:
    double length;
    double width;
public:
    // 构造函数,默认值为1
    Rectangle() : length(1), width(1) {}

    // 设置长度,并验证范围(0.0, 20.0),成功返回true,否则false
    bool setLength(double l) {
        if (l > 0.0 && l < 20.0) {
            length = l;
            return true;
        }
        return false;
    }

    // 设置宽度,并验证范围(0.0, 20.0)
    bool setWidth(double w) {
        if (w > 0.0 && w < 20.0) {
            width = w;
            return true;
        }
        return false;
    }

    // get方法
    double getLength() const { return length; }
    double getWidth() const { return width; }

    // 只读属性:周长(没有set方法)
    double getPerimeter() const {
        return 2 * (length + width);
    }

    // 只读属性:面积(没有set方法)
    double getArea() const {
        return length * width;
    }
};

int main() {
    double l, w;
    cin >> l >> w;

    Rectangle rect;   // 创建Rectangle对象,默认长宽都是1

    // 调用set方法,同时完成赋值和校验
    if (rect.setLength(l) && rect.setWidth(w)) {
        cout << fixed << setprecision(2);
        cout << "the perimeter is " << rect.getPerimeter()
             << ",the area is " << rect.getArea() << ".";
    } else {
        cout << "The value you input is not within the required range." << endl;
    }
    return 0;
}

用C++来面向过程编程,相当于为原本 c 的面向过程提供了更加好用的结构体,各种函数,容器。使得原本面向过程的编程语言不断进化,可以更简单的解决更复杂的问题。但是其与面向对象的编程思想从根源上就是不同的。