我正在阅读一些C++文本.在一个例子中,写的文字:
class Student {
int no;
char grade[M+1];
public:
Student();
Student(int, const char*);
const Student& set(int, const char*);
void display() const;
};
Student::Student() {
no = 0;
grade[0] = '\0';
}
Student::Student(int n, const char* g) {
*this = Student(); // initialize to empty
set(n, g); // validate, reset if ok
}
Run Code Online (Sandbox Code Playgroud)
我不明白这一行: *this = Student();
为什么我们必须这样做,而只是调用Student();也会调用默认构造函数?谢谢
无法直接调用默认构造函数(C++ FAQ).即.
Student::Student(int n, const char* g){
Student();
set(n, g); // validate, reset if ok
}
Run Code Online (Sandbox Code Playgroud)
不起作用.但是,我也不确定你的解决方案.
*this = Student()
Run Code Online (Sandbox Code Playgroud)
会打电话Student::operator=(const Student&).在这个特定的类中,它是可以的(该函数是默认的成员副本),但它可能不是一般的,因为在调用该方法时,Student对象只是"部分构造".
最好有私有init函数
void Student::init() {
no = 0;
grade[0] = '\0';
}
Run Code Online (Sandbox Code Playgroud)
并从两个构造函数中调用它.
| 归档时间: |
|
| 查看次数: |
187 次 |
| 最近记录: |