基础语法——类、结构体、链表

类和结构体基本一样,唯一的不同就是:如果不声明是private或public,则类默认为private,结构体默认为public。

类的定义

#include<iostream>

using namespace std;

class Person{
    private: //私有型,只能在类里调用
        int age,height;
        double money
        string books[100];
        int get_height(){
            return height;
        }
    
    public: //公共型,可以在类里和类外调用
        stirng name;
        void say(){
            cout << "I`m" << name << endl;
        }
        int get_age(){
            return age;
        }
        void add_money(double x){
            money += x;
        }
        private:
            string books[100];
            
}; //末尾一定要加 ;

int main(){
    
    return 0;
}

类的使用

#include<iostream>

using namespace std;

class Person{
    private: //私有型,只能在类里调用
        int age,height;
        double money
        string books[100];
        int get_height(){
            return height;
        }
    
    public: //公共型,可以在类里和类外调用
        stirng name;
        void say(){
            cout << "I`m" << name << endl;
        }
        int get_age(){
            return age;
        }
        void add_money(double x){
            money += x;
        }
        private:
            string books[100];
            
}; //末尾一定要加 ;

int main(){
    Person c;
    c.name = "lxy";
//  c.age = 18; // 错误的,age为私有变量
    c.add_money(1000000);
    cout << c.get_age() << endl;
    return 0;
}

类的构造函数

#include<iostream>

using namespace std;

struct Person{
    int age,height;
    double money;
    Person(int _age,int _height,double _money){
        age = _age;
        height = _height;
        money = _money;
    } //构造函数
    Person(int _age,int _height,double _money) : age(_age),height(_height),money(_money) {} //另一种定义构造函数的方式
};

int main(){
    Person c{19,175,10000000};
    cout << c.age << endl;
    return 0;
}

链表

#include<iostream>

using namespace std;

struct Node{
    int val;
    Node* next;
    Node(int _val) : val(_val),next(NULL) {}
    
};

int main(){
    Node* p = new Node(1); //new:动态开辟一个结构体
    auto q = new Node(2); //auto猜类型,即为Node*
    auto o = new Node(3);
    p->next = p; //p的next指针指向自己,形成自环。ps:如果p是一个指针,要用"->"来调用成员标量,如果不是指针,则可以通过p.next来调用
    p->next = q; //p中的next指针指向q,即构造一个链表
    q->next = o;
    Node* head = p;
    
    //头插一个节点
    Node* u = new Node(4);
    u->next = head;
    head = u;
    
    //删除节点
    head->next = head->next->next;
    
    //链表的遍历方式
    for(Node* i = head;i;i = i->next){
        cout << i->val << endl;
    }
    
    return 0;
}

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

还好我是c语言大佬

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

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

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

打赏作者

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

抵扣说明:

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

余额充值