【学习笔记】C++类,简单实例

目录

类实例1:

类实例2:

3.类实例,指针,引用和类

4.C++类的分文件编写


​​​​​​​

类实例1:

#include <iostream>
#include <string>
using namespace std;

const double PI =3.14;

class Circle
{
//访问权限
public:
//属性
int m_r;

//行为
double calculateZC()
{

return 2*PI*m_r;

}


};



int main()
{
  Circle c1;
  c1.m_r=10;

  cout<<"圆的周长= "<<c1.calculateZC()<<endl;

    system("pause");

    return 0;
}

类实例2:

#include <iostream>
#include <string>
using namespace std;

const double PI = 3.14;

class Student
{
    //访问权限
public:
    //属性
    string name, ID;

    //行为
    void printInfo()
    {

        cout << "学生姓名\t" << name << "\tID: " << ID << endl;
    }
};

int main()
{
    Student s1;
    s1.name = "hslk";
    s1.ID = "201447";
    s1.printInfo();

    system("pause");

    return 0;
}

3.类实例,指针,引用和类

#include <iostream>
#include <string>
using namespace std;

const double PI = 3.14;

class Student
{

public:
    void getname()
    {
        cout << "姓名为 " << name << endl;
    }
    void setInfo()
    {
        cout << "请输入姓名" << endl;
        cin >> name;
        cout << "请输入id" << endl;
        cin >> ID;
    }
    void printInfo()
    {

        cout << "学生姓名\t" << name << "\tID: " << ID << endl;
    }

    //访问权限
private:
    string name, ID;
};

void issame(Student *s1)
{
s1->getname();//与结构体使用指针相同

}

int main()
{
    Student s1;
    s1.setInfo();
    s1.getname();
    s1.printInfo();
    issame(&s1);

    system("pause");

    return 0;
}

4.C++类的分文件编写

hello.h头文件

#pragma once//防止头文件重复包含
#include <iostream>
using namespace std;
//类 
class Student
{

public:
    void getname();
   
    void setInfo();
    
    void printInfo();
   

    //访问权限
private:
    string name, ID;
};

源文件

#include"hello.h"




    void Student::getname()//Student::为作用域(namespace)
    {
        cout << "姓名为 " << Student::name << endl;
    }

    void Student::setInfo()
    {
        cout << "请输入姓名" << endl;
        cin >> Student::name;
        cout << "请输入id" << endl;
        cin >> Student::ID;
    }

    void Student::printInfo()
    {

        cout << "学生姓名\t" << Student::name << "\tID: " << Student::ID << endl;
    }

main()

#include <iostream>
#include <string>
#include "hello.h"
using namespace std;
void issame(Student *s1)
{
s1->getname();

}

int main()
{
    Student s1;
    s1.setInfo();
    s1.getname();
    s1.printInfo();
    issame(&s1);

    system("pause");
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值