这是来自 C++20 规范 ( [basic.life]/8 )的代码示例:
struct C {
int i;
void f();
const C& operator=( const C& );
};
const C& C::operator=( const C& other) {
if ( this != &other ) {
this->~C(); // lifetime of *this ends
new (this) C(other); // new object of type C created
f(); // well-defined
}
return *this;
}
int main() {
C c1;
C c2;
c1 = c2; // well-defined
c1.f(); // well-defined; c1 refers to a new object of type …Run Code Online (Sandbox Code Playgroud) C++ 类是否有可能像我们在 Java 中一样包含自己类型的实例?例如,这样的事情:
public class A {
private A a1;
private A a2;
A getA1(){
return a1;
}
A getA2(){
return a2;
}
void setA1(A a1){
this.a1 = a1;
}
void setA2(A a2){
this.a2 = a2;
}
}
Run Code Online (Sandbox Code Playgroud)
现在我想在 C++ 中做同样的事情或解决方法。