java、C++、python三种语言对比之类 class

需求

实现一个简单的Student类,

  • 属性

    • name
    • age
  • 方法

    • 默认构造函数
    • 带参数的构造函数
    • 两个属性的get和set方法
  • 测试,实现main方法

    • 测试Student类中的方法都可以用

java定义一个Class

public class Student {

    private String name;
    private int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }   
}

测试代码

public static void main(String[] args) {
        Student s1 = new Student();
        s1.setAge(12);
        s1.setName("nihao");
        System.out.println("name = "+s1.getName());
        System.out.println("age = "+s1.getAge());


        Student s2 = new Student("baidu", 2018);
        System.out.println("name = "+s2.getName());
        System.out.println("age = "+s2.getAge());

    }

C++

#include "iostream"
#include <stdio.h>
#include "string.h"
using namespace std;
class Student {

private:
    string name;
    int age;


public:
    Student() {
    }
    Student(string n, int a) : name(n), age(a) {
    }

    string getName() {
        return name;
    }

    void setName(string name) {
        this->name = name;
    }

    int getAge() {
        return age;
    }

    void setAge(int age) {
        this->age = age;
    }

};

测试代码

int main() {
        Student s1;
        s1.setAge(1);
        s1.setName("name");
        cout<<"name = "<<s1.getName().c_str()<<endl;;
        cout<<"age = "<<s1.getAge()<<endl;;

        //Student s2 = new Student("baidu", 2018);
        Student s2("name2", 2);
        cout<<"name = "<<s2.getName().c_str()<<endl;;
        cout<<"age = "<<s2.getAge()<<endl;


        /*指针对象都是new出来的*/
        Student* s3 = new Student();
        s3->setAge(3);
        s3->setName("name3");
        cout<<"name = "<<s3->getName().c_str()<<endl;;
        cout<<"age = "<<s3->getAge()<<endl;;

        Student* s4 = new Student("name4", 4);
        cout<<"name = "<<s4->getName().c_str()<<endl;;
        cout<<"age = "<<s4->getAge()<<endl;

    }

总结

  • 新建对象
    • java新建对象必须通过new关键字,如Student s1 = new Student();
    • C++定义新的对象不需要new关键字,定义新对象的指针时需要new关键字;
    • python
  • 成员的访问属性

    • java每个成员前面都要加上访问属性或者默认权限;
    • C++在一组权限相同的成员只需要在最前面写访问权限符号,有效区域是遇到下一个访问权限符;
    • 在Python中没有显式的private和public限定符,如果要将一个方法声明为private的,只要在方法名前面加上__即可;
  • 访问成员

    • java访问成员都是点运算符(.)
    • C++对象访问成员是点运算符(.),指针访问成员是箭头运算符(->)
    • python访问访问成员都是点运算符(.)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值