gpt4 book ai didi

c++ - 从覆盖访问派生类的成员元素

转载 作者:行者123 更新时间:2023-12-03 07:11:59 24 4
gpt4 key购买 nike

覆盖复制运算符重载函数后如何访问派生类?
我是 OOP C++ 的新手,所以我不确定是否将运算符重载定义为纯虚拟作品;否则,我将如何强制它们在派生类中定义?
我在这里使用的示例是 Matrix 接口(interface)和特定于行的实现。

class IMatrix
{
public:
virtual IMatrix& operator=(const IMatrix& matrix) = 0;
};

class RMMatrix : public IMatrix
{
long double* data;
public:
RMMatrix& operator=(const IMatrix& other) override
{
// how to get access to data here then ?
};
};

最佳答案

如评论中所述,您可以使用 dynamic_cast在传递的引用上测试它是否引用了实际的 RMMatrix目的。像这样的东西:

    RMMatrix& operator=(const IMatrix& other) override {
const RMMatrix& test = dynamic_cast<const RMMatrix&>(other);
data = test.data;
return *this; // return a reference to "this" object!
}
然而(也在评论中指出), dynamic_cast如果引用失败(即如果传递的参数不是对 RMMatrix 的引用),引用将引发异常。
如果您想避免抛出异常,并添加一些其他错误处理行为,那么您可以使用指针 dynamic_cast在传递参数的地址上。这将返回 nullptr失败时,而不是抛出异常:
class IMatrix {
public:
virtual IMatrix& operator=(const IMatrix& matrix) = 0;
virtual ~IMatrix() = default; // We should add a VIRTUAL destructor!
};

class RMMatrix : public IMatrix {
long double* data;
public:
RMMatrix& operator=(const IMatrix& other) override {
const RMMatrix* testPtr = dynamic_cast<const RMMatrix*>(&other); // Test cast the address!
if (testPtr != nullptr) { // Passed argument is a VALID reference...
data = testPtr->data;
// You would really need something safer here, rather than just copying the data pointer!
}
else { // Passed argument is NOT a reference to an RMMatrix...
// Handle 'error': Leave "data" unchanged, set it to "nullptr", or throw an exception?
//...
}
return *this; // return a reference to "this" object!
}
~RMMatrix() override { // Override VIRTUAL destructor!
delete data; // Maybe?
}
};

关于c++ - 从覆盖访问派生类的成员元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64668027/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com