问个构造函数的问题
#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 = '\0';
}
protected:
char name;
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 = '\0';
}
可写成:
Student(char *pName="noName",int ssID=0)
{
cout << "constructing student " << pName << endl;
strcpy(name,pName);
name = '\0';
}
表明将调用StudentID的默认构造函数,主函数中两条创建 Student对象的语句都遇到不能匹配StudentI D构造函数的编译错误.
但是我上式把 :id(ssID) 去掉都没有错误, 为什么会这样呢? 因为对Student的构造函数传入的ssID在去掉:id(ssID)之后就根本不产生作用了
页:
[1]