構造函數的三種調用方法


括號法

就是直接用普通函數的調用方式

#include<iostream>
#include<string>
using namespace std;
class Student
{
private:
    int age;
    int *height;
public:
    Student(int age1, int height1){
        age = age1;
        height = new int(height1);
    }
    void printAge(){
        cout<<age<<endl;
    }
};
int main(){
    system("chcp 65001");
    Student stu1(13,135);
    stu1.printAge();
    system("pause");
    return 0;
}

顯示法

將類名進行調用,然后傳給一個變量

#include<iostream>
#include<string>
using namespace std;
class Student
{
private:
    int age;
    int *height;
public:
    Student(int age1, int height1){
        age = age1;
        height = new int(height1);
    }
    void printAge(){
        cout<<age<<endl;
    }
};
int main(){
    system("chcp 65001");
    Student stu1 = Student(13,135);
    stu1.printAge();
    system("pause");
    return 0;
}

隱式方法

將參數放在等號后面進行調用

#include<iostream>
#include<string>
using namespace std;
class Student
{
private:
    int age;
    int height;
public:
    Student(int age1,int height1){
        age = age1;
        height = height1;
    }
    void printAge(){
        cout<<age<<endl;
    }
};
int main(){
    system("chcp 65001");
    Student stu1 = {13,150};//多個參數以數組形式傳入
    stu1.printAge();

    return 0;
}

 


免責聲明!

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



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