zoukankan      html  css  js  c++  java
  • 【C++】类的两种实例化方法

    直接上代码:

    #include<stdio.h>
    #include<string>
    #include<iostream>
    using namespace std;
    class Student
    {
    
    private:
        int age;
        string name;
    
    public:
        Student(int, string);
        void show(int _age, string _name);
        void show2();
    };
    
    Student::Student(int _age, string _name)
    {
        this->age = _age;
        this->name = _name;
    }
    
    void Student::show(int _age, string _name)
    {
        //printf("Age : %d
     Name : %s", _age, _name);
        cout<<"Age : "<<_age<<"
    Name : "<<_name<<endl;
    }
    
    void Student::show2()
    {
        cout<<"Age : "<<this->age<<"
    Name : "<<this->name<<endl;
    }
    
    int main()
    {
        Student s(16, "puyangsky");
        s.show(14, "puyangsky");
        s.show2();
    
    
        Student *s1 = new Student(16, "puyangsky");
        s1->show2();
        return 0;
    }

    定义了一个Student类,在main方法中使用了两种方法去实例化对象,第一个对象s是直接用 类名 对象名(参数1,..)来定义的,第二个对象是通过指针定义,类名 *指针名 = new 类名(参数1,..)

    另外,如果直接通过类名定义一个对象的话,对象使用其成员变量和函数时是通过点的形式

    Student s1(13, "Amy");
    s1.age = 15;
    s1.show();

    如果是通过指针定义对象的话,则是通过->来访问其变量和函数

    Student *s2 = new Student(14, "Amy");
    s2->age = 12;
    s2->show();
  • 相关阅读:
    EditPlus保存文件时不生成其备份文件的方法
    一台电脑同时运行多个tomcat配置方法
    Dom4j写XML
    .....
    编程备忘录
    背包问题
    chrome新版不再支持-webkit-text-size-adjust
    安装grunt需要的grunt插件
    初学web前端
    心情烦躁、、
  • 原文地址:https://www.cnblogs.com/puyangsky/p/5234664.html
Copyright © 2011-2022 走看看