求助"拷贝构造函数"的问题
class Student
{
public:
Student(char* pName="no name", int ssId=0)
{
id=ssId;
strcpy(name,pName);
cout<<"constructing new student"<<pName<<endl;
}
Student(Student& s)
{
cout<<"Construting copy of"<<s.name<<endl;
strcpy(name,s.name);
id=s.id;
cout<<"the id is"<<id<<endl;
}
~Student()
{
cout<<"Destructing"<<name<<endl;
}
protected:
char name[40];
int id;
};
void fn(Student s)
{
cout<<"In function fn()\n";
}
void main()
{
Student randy("Randy",1234);
cout<<"Calling fn()\n";
fn(randy);
cout<<"Returned from fn()\n";
}
看钱能书的时候碰到一个问题,在上面主函数中调用fn(randy)函数时,用到拷贝构造函数,但是在拷贝构造函数Student(Student&s)中,用类Student的对象s引用了保护变量char name[40],即s.name;但是根据类的封装性,对象是不能引用私有/保护变量的,只有成员函数才可以,这里用对象s引用保护变量不知是为什么?谢谢