使用构造函数时何时必须使用"this C++?
When do I have to use 'this' when using C++ constructors?
class Int {
int n;
public:
Int(int n) {
this->n = n;
}
};
与
class Int {
int n;
public:
Int(int n) : n(n){
}
};
这两者之间的本质区别是什么,在创建给定类的新对象时何时应该使用 this
关键字?
最大的区别是第二种是推荐的方法,因为它避免了双重初始化属性。int
是一个微不足道的情况,但你可以想象你可能有一些昂贵的结构,会被初始化两次:
Complicated(const HeavyObject& _h) : h(_h) {
// h only initialized once
}
Complicated(const HeavyObject& _h) {
// h already initialized with default constructor
// Copy to object, potentially initializing all over again.
this->h = _h;
}
相关文章:
- 表示"accepting anything for this template argument" C++概念的通配符
- 为什么使用 "this" 指针调用派生成员函数?
- C++错误:"error: int aaa::bbb is protected within this context"
- 我可以将调用类的"this"传递给 lambda 函数吗?
- 创建具有 new in 函数和"this is nullptr"异常的对象
- 关于C++中具有多重继承"this"指针的说明
- 在noexcept 规范中是否允许使用"this"?
- 如何修复"error: ‘_1’ was not declared in this scope"?
- C++调用具有 *this 属性的单个帮助程序函数
- Doees the 'this' 指针参与虚函数的多态行为
- 在 c++ 中正确定义"this"关键字?
- 在什么情况下,两个堆栈分配的结构对象的 this 点指向同一个地址?
- "Unable to start debugging. No process is associated with this object." - 在Visual Studio Code中使用GDB
- QObject::连接无法将信号连接到*this*对象的插槽
- 析构函数中的"delete this"
- 为什么成员函数内的"this"指针为空?
- 为什么我需要在转换构造函数上引用 this->?
- "this"指针的值在对象的生存期内是否恒定?
- C++ "Invalid use of 'this' in non-member function" ,
- 如何将'this'指针传递给C++ WinAPI 线程?