18.C++构造函数的重载

来源:互联网 发布:小米盒子看网络电视吗 编辑:程序博客网 时间:2024/05/24 01:46
#include <iostream>#include <string.h>class Student  //定义Stduent类{private:   //  声明私有数据成名    char name[10];    int age;    char sex;public:    Student();   //声明无参数的构造函数    //声明带参数的构造函数,构造函数可以重载    Student(char newName[10],int newAge, char newSex);    void output();};Student::Student()//定义无参数的构造函数{    strcpy(name, "wang");    age=20;    sex='F';}//定义带参数的构造函数Student::Student(char newName[10],int newAge, char newSex){    strcpy(name, newName);    age=newAge;    sex=newSex;}void Student::output(){    std::cout<<"姓名:"<<name<<",年龄"<<age<<",性别"<<sex<<std::endl;}int main(int argc, const char * argv[]){    Student stu1("li wei",23,'F');//定义对象stu1,系统自动调用带参数的构造函数    Student stu2;//定义对象stu2,系统自动调用不带参数的构造函数    stu1.output();    stu2.output();//姓名:wang,年龄20,性别F    return 0;}

原创粉丝点击