- 注册时间
- 2004-10-13
- 最后登录
- 2019-5-15
⑧专业
*永恒国度*
- 积分
- 14145
|
- #include<iostream>
- #include<string.h>
- using namespace std;
- class StudentID
- {
- public:
- StudentID(int id=0)
- {
- value = id;
- cout << "assigning student id " << value << endl;
- }
- ~StudentID()
- {
-
- cout << "destructing id " << value << endl;
- }
- protected:
- int value;
- };
- class Student
- {
- public:
- Student(char *pName="noName",int ssID=0):id(ssID)
- {
- cout << "constructing student " << pName << endl;
- strcpy(name,pName);
- name[sizeof(name)-1] = '\0';
-
- }
- protected:
- char name[20];
- StudentID id;
- };
- void main()
- {
- Student s("Randy",1000);
- Student t("Jenny");
- }
复制代码
像以上这个程序, Student(char *pName="noName",int ssID=0):id(ssID) 这里是对冒号后面的数据成员的构造函数进行调用.
而书上说Student构造函数冒号后面如果是 id()形式,表示调用 StudnetID的默认构造函数,且可以省略,
即:- Student(char *pName="noName",int ssID=0):id()
- {
- cout << "constructing student " << pName << endl;
- strcpy(name,pName);
- name[sizeof(name)-1] = '\0';
-
- }
- 可写成:
- Student(char *pName="noName",int ssID=0)
- {
- cout << "constructing student " << pName << endl;
- strcpy(name,pName);
- name[sizeof(name)-1] = '\0';
-
- }
复制代码 表明将调用StudentID的默认构造函数,主函数中两条创建 Student对象的语句都遇到不能匹配StudentI D构造函数的编译错误.
但是我上式把 :id(ssID) 去掉都没有错误, 为什么会这样呢? |
|