关于在 C++ 中将默认构造函数分配给 *this 的问题?
我正在阅读一些 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
}
我不明白这一行:*this = Student();
为什么我们必须这样做,而只是调用Student();
code> 也使默认构造函数被调用? 谢谢
I am reading some C++ text. In an example, the text written:
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
}
I don't understand this line: *this = Student();
Why do we have to do that, while just calling Student();
also makes the default constructor invoked?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
无法直接调用默认构造函数(C++ 常见问题)。 IE。
不起作用。不过我也不确定你有什么解决方案。
将调用
Student::operator=(const Student&)
。在这个特定的类中,这是可以的(该函数是默认的成员副本),但通常可能不是这样,因为调用该方法时,Student 对象只是“部分构造”。最好有一个私有的 init 函数
并从两个构造函数中调用它。
It's not possible to call the default constructor directly (C++ FAQ). ie.
doesn't work. However I'm not sure about the solution you have, either.
will call
Student::operator=(const Student&)
. In this particular class it's OK (that function is the default member copy) but it might not be in general, because the Student object is only 'partly constructed' when that method is called.Better to have a private init function
and call it from both constructors.
虽然,恕我直言,最好使用通用的初始化函数,如下所示:
这将避免不必要的对象创建。
Although, imho, it would be better to use common initialization function, something like this:
That would avoid unnecessary creation of objects.
它构造一个临时
Student
对象,然后将其复制到*this
。我只是在第二个构造函数中将成员变量初始化为空。这个想法是,您不必编写两次将成员变量初始化为空的相同代码,但这里的问题非常简单。It constructs a temporary
Student
object, and then copies it to*this
. I would just initialize the member variables to empty in the second constructor though. The idea is that you don't have to write the same code that initializes the member variables as empty twice though, but it is quite trivial problem here.*this = Student();
只是根据调用的默认构造函数初始化成员变量。应避免此类设计,因为它会创建临时内容并复制其内容。使用如下所示的内容:
*this = Student();
is just to initialize the member variables with respect to default constructor called. Such design should be avoided, as it creates temporary and copies it contents.Use something like below: