【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\n Name : %s", _age, _name);
    cout<<"Age : "<<_age<<"\nName : "<<_name<<endl;
}

void Student::show2()
{
    cout<<"Age : "<<this->age<<"\nName : "<<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();

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM