gpt4 book ai didi

c++ - 虚拟分配

转载 作者:太空狗 更新时间:2023-10-29 20:16:27 26 4
gpt4 key购买 nike

我在理解这个问题时遇到了一些问题。

我有一个类:

class StringProperty { //snipped...
protected:
std::string s;
public:
virtual StringProperty& operator= (const std::string &x) {
s = x;
return *this;
}
virtual StringProperty& foo(const std::string &x) {
s = x;
return *this;
}
};

这个类(它有更多的方法,为简单起见被剪掉了)应该作为一个字符串。

当我从中得出时:

class Test : public StringProperty { };

我想做这样的事情:

Test x;
x = "test";

但是,这失败得很惨(无法编译):

error: no match for ‘operator=’ in ‘x = "test"’

尽管如此,如果我使用

x.foo("test");

它有效。我有兴趣了解它失败的原因,因为对我来说这两个功能是相同的。

谢谢。

最佳答案

您的 Test 类包含一个隐式声明的复制赋值运算符(以及默认构造函数、复制构造函数和析构函数)。这隐藏了基类中的那个。为了将其视为重载,您必须使其在派生类中可访问:

class Test : public StringProperty {
public:
using StringProperty::operator=;
};

关于c++ - 虚拟分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9504106/

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