C++类和对象

 

#include "iostream"

using namespace std;

const double PI = 3.14;

/*
 * 设计一个圆类,求圆的周长
 *
 */

class Circle {
    //访问权限
    //公共权限
public:
    //属性
    //半径
    int radius;

    //行为
    //获取圆的周长
    double calculateZC() {
        return 2 * PI * radius;
    }
};

int main() {
    //通过类创建具体的对象
//    Circle c = {10}; 或者如下
    Circle c;
    c.radius = 10;
    cout << "圆的周长:" << c.calculateZC() << endl;
    return 0;
}
#include "iostream"

using namespace std;

class Student {
public:
    string name;
    int id;

    void showStudent() {
        cout << "姓名:" << name << "id:" << id << endl;
    }

};

int main() {
    Student stu;
    stu.name = "bob";
    stu.id = 12321;
    stu.showStudent();
    return 0;
}

访问权限

保护权限,继承时,子类也能访问。

是有权限,继承时,子类不能访问。

#include "iostream"

using namespace std;

class Student {
public:
    string name;
protected:
    string car;
private:
    string password;
public:
    void init() {
        name = "fadfad";
        car = "car";
        password = "a123412";
    }
};

int main() {
    Student stu;
    stu.init();
    stu.name = "1";
//    stu.car = "1";//保护权限,在类外部访问不到
//    stu.password = "1";//私有权限,在类外部访问不到
    return 0;
}

#include "iostream"

using namespace std;

class Student {
    int age;//默认私有
};

struct Teacher {
    int age;//默认公共
};


int main() {
    Student stu;
    Teacher t;
//    stu.age = 1;//报错
    t.age = 1;
    return 0;
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值