用C ++中的this指针初始化一个类对象

问题描述 投票:0回答:1

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;
};
c++ c++11 this this-pointer
1个回答
2
投票

没有问题。成员函数void import(void);不是常数函数。在此语句中

*this = B.create();

使用了默认的副本分配运算符。

还有更好的方法吗?

例如,更好的方法是不使用成员函数,而仅对类的对象使用赋值语句

c_A c1 = { 10, 20 };

c1 = c_B().create();
© www.soinside.com 2019 - 2024. All rights reserved.