c++成员初始化和构造函数
2016-03-30 10:36
591 查看
1 C++成员变量初始化
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; };//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; }
相关文章推荐
- C语言——可变参数
- C语言数据类型取值范围
- C++ 类和对象浅解
- C++ 对象复制 内存拷贝
- 【poj 1836】Alignment 题意&题解&代码(C++)
- c++ constexpr
- C语言复习1之指针
- C++ nullptr
- C++ 函数指针批处理
- c++ 函数指针
- C++ 内联函数 浅解
- C/C++ 副作用和序列点
- C++ 函数参数的默认值
- 程冬冬 2010.12.22 C语言程序-收发EMAIL
- 格式化 C语言源码——命令indent
- 【poj 3267】The Cow Lexicon 题意&题解&代码(C++)
- C++ 函数匹配和作用域声明
- CFile处理(读取路径文件内容,保存在表里面)
- 【C/C++】任意大于1的整数分解成素数因子乘积的形式
- c++ vector 迭代器 demo