在 C++ 中,我想使用另一个类方法的结果来初始化(或更改)一个类对象。我可以使用 this 指针吗?有没有更好的办法?
虚拟示例:
class c_A {
public:
int a, b;
void import(void);
};
class c_B {
public:
c_A create(void);
};
void c_A::import(void) {
c_B B;
*this = B.create();
};
c_A c_B::create(void) {
c_A A;
A.a = A.b = 0;
return A;
};
最佳答案
没有问题。成员函数void import(void);
不是常量函数。在这个语句中
*this = B.create();
使用了默认的复制赋值运算符。
Is there a better way?
更好的方法是不使用成员函数,而只是为类的对象使用赋值语句,例如
c_A c1 = { 10, 20 };
c1 = c_B().create();
关于c++ - 在 C++ 中使用 this 指针初始化一个类对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58994186/