构造函数的三种调用方法


括号法

就是直接用普通函数的调用方式

#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