C++ 如何通过从派生类复制方法来设置基类字段? 类基{ 公众: 浮子a、b; }; 派生类:公共基{ 公众: int someInteger,otherInt; void元素(向量和myArray,int i){ this=myArray[i-1];/??如何??? } void simpleMethodOfAssigningNthElement(向量和myArray,int i){ a=myArray[i-1].a; b=myArray[i-1].b; } };

C++ 如何通过从派生类复制方法来设置基类字段? 类基{ 公众: 浮子a、b; }; 派生类:公共基{ 公众: int someInteger,otherInt; void元素(向量和myArray,int i){ this=myArray[i-1];/??如何??? } void simpleMethodOfAssigningNthElement(向量和myArray,int i){ a=myArray[i-1].a; b=myArray[i-1].b; } };,c++,inheritance,C++,Inheritance,如何从myArray直接复制派生类中描述基类的值? 也许最好像在“simpleMethodOfAssigningNthElement”中那样做? 哪个更快?您不能像在assignnthement中尝试的那样执行,它只需要像simpleMethodofasigningnthement那样实现。您不能像assignnthement()中那样将基类对象分配给派生类对象,这将导致编译错误 请注意,允许使用相反的方式,即:您可以将派生类对象指定给基类对象,但这最终会分割派生类对象的成员。这种现象称为对象切

如何从myArray直接复制派生类中描述基类的值? 也许最好像在“simpleMethodOfAssigningNthElement”中那样做?
哪个更快?

您不能像在
assignnthement
中尝试的那样执行,它只需要像
simpleMethodofasigningnthement
那样实现。

您不能像
assignnthement()
中那样将基类对象分配给派生类对象,这将导致编译错误


请注意,允许使用相反的方式,即:您可以将派生类对象指定给基类对象,但这最终会分割派生类对象的成员。这种现象称为对象切片

您可以使用一些C-hack,但这是一种糟糕的方法。最好的方法是SimpleMethodofsSigningnthElement。 如果需要,可以为
派生类重载
运算符=

class Base{
public:
float a,b;
};

class Derived:public Base{
public:
int someInteger, otherInt;

void assignNthElement(vector<Base> &myArray,int i){
this=myArray[i-1];//??? How ???
}

void simpleMethodOfAssigningNthElement(vector<Base>&myArray,int i){
a=myArray[i-1].a;
b=myArray[i-1].b;
}


};
类基{
公众:
浮子a、b;
};
派生类:公共基{
公众:
int someInteger,otherInt;
void元素(向量和myArray,int i){
this=myArray[i-1];//现在可以了
}
常量派生运算符和运算符=(常量基和基){
a=基准。a;
b=基准。b;
}
};
class Base{
public:
float a,b;
};

class Derived : public Base{
public:
    int someInteger, otherInt;

    void assignNthElement(vector<Base> &myArray,int i){
        this = myArray[i-1];// It's OK now
    }

    const Derived & operator=(const Base &base){
        a=base.a;
        b=base.b;
    }

};