C++构造函数

#include <iostream>
#include <string>
using namespace std;

class Student {
    /*
    构造函数语法:类名(参数表){   } 
    注意:函数名与类名相同,没有返回值
    构造函数在创建对象时,会自动执行,主要用来初始化
    */
public:
    Student(const string& name1,int age1,int no1) {
        //注意:公有
        name = name1;
        age = age1;
        no = no1;
    }
private:
    string name;
public:
    int age;
    int no;
    
    void who(void) {
        cout << "我叫" << name << endl;
        cout << "今年" << age << "" << endl;
        cout << "学号是:" << no << endl;
    }
};

int main()
{
    Student s("张三", 25, 10011);  //创建对象并初始化
    s.who();
    return 0;
}

原文地址:https://www.cnblogs.com/liming19680104/p/13475003.html