zoukankan      html  css  js  c++  java
  • c++成员初始化和构造函数

    1 C++成员变量初始化

    #include<iostream>
    #include <string.h>
    using namespace std;
    struct Student{
        int id=1001;            //成员变量或对象
        char name[64]="zhangsan";
        int age=20;
        int score=99;
    };//end class Student
    
    int main()
    {
    //  Student stu={1001,"zhangsan",20,99};
        Student stu1;
        cout<<stu1.name<<endl;
        return 0;
    }

    2 C++ 构造函数

    #include<iostream>
    #include <string.h>
    using namespace std;
    struct Student{
        int id=1001;            //成员变量或对象
        char name[64];//="zhangsan";
        int age=20;
        int score=99;
    
        //构造函数的名字和该类的名字相同;
        //构造函数没有返回值,连void都不用;
        //构造函数可以重载
        //可以有默认构造函数:如果程序员没有定义任何构造函数,那么系统会定义个默认构造函数,被叫做合成构造函数
        //如果程序员定义了带参数的构造函数,那么系统就不再定义合成构造函数;如果程序员还有需要,那么必须自己定义 
    #if 1
        Student(){cout<<"student default construction!"<<endl;}
        Student(int i,const char*n, int a,int s){
            id=i;strcpy(name,n);age=a;score=s;
        }
        Student(int i,const char*n, int a){
            id=i;strcpy(name,n);age=a;
        }
    #endif
    };//end class Student
    
    int main()
    {
    //  Student stu={1001,"zhangsan",20,99};
        Student stu1(1002,"lisi",20);
    //  Student stu;
    //  cout<<stu1.name<<endl;
        return 0;
    }
    
  • 相关阅读:
    辗转相除法求最大公约数
    洛谷——P2615 神奇的幻方 【Noip2015 day1t1】
    二分图的一大泼基础题
    HDU——T 1150 Machine Schedule
    HDU——T 1068 Girls and Boys
    POJ——T 3020 Antenna Placement
    Web框架Django(二)
    February 25 2017 Week 8 Saturday
    February 24 2017 Week 8 Friday
    February 23 2017 Week 8 Thursday
  • 原文地址:https://www.cnblogs.com/Sico2Sico/p/5384260.html
Copyright © 2011-2022 走看看