如何继承“operator =” [英] How to Inherit "operator ="

查看:150
本文介绍了如何继承“operator =”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一种情况让我觉得operator =没有被继承,但也许我无法理解标准。这是一个说明问题的最小例子:

I have a situation that makes me think that "operator =" is not being inherited, but perhaps I fail to understand the standard. Here is a minimal example that illustrates the problem:

struct Foo {
    Foo &operator =(double const val);
};

struct Bar : public Foo { };

int main(int const argc, char const *const argv[]) {
    Bar a;
    Foo b(a);

    b = 4.5; // No issue
    a = 4.5; // error C2679: binary '=' : no operator found which takes a right-hand
             // operand of type 'double' (or there is no acceptable conversion)

    return 0;
}



我正在使用Visual Studio 2010,以防这是我的编译器特有的行为。谢谢!


I am using Visual Studio 2010 in case this is behavior specific to my compiler. Thanks!

推荐答案

它当然是作为一切继承的。唯一的问题是您定义的运算符是默认运算符隐藏。如果将 a 强制转换为 Foo ,则可以轻松查看。另请注意, Foo=返回类型 Foo ,您的代码将要求它返回酒吧。没有这样的操作员,这个事实由你得到的错误表示。



对于某些背景,请参阅:

http://en.wikipedia.org/wiki/Covariance_and_contravariance_%28computer_science%29 [ ^ ],

http://fedelebron.com/categorical-view-covariance-and-convvariance-c [ ^ ],

http://www.cpptips.com/Covariance.html [ ^ ],

http://stackoverflow.com/questions/1260757/when-is-c-covariance-the-best-solution [ ^ ](请参阅最后答案),

http:// itremarks .wordpress.com / 2011/09/13 / c-covariance-in-virtual-functions / [ ^ ]。



-SA
It is of course inherited as everything. The only problem is that the operator you defined is hidden by the default operator. You can easily see it if you cast a to Foo. Also note that Foo "=" returns the type Foo, and your code would require it to return Bar. There is no such operator, and this fact is indicated by the error you got.

For some background, please see:
http://en.wikipedia.org/wiki/Covariance_and_contravariance_%28computer_science%29[^],
http://fedelebron.com/categorical-view-covariance-and-contravariance-c[^],
http://www.cpptips.com/Covariance.html[^],
http://stackoverflow.com/questions/1260757/when-is-c-covariance-the-best-solution[^] (please see the last answer),
http://itremarks.wordpress.com/2011/09/13/c-covariance-in-virtual-functions/[^].

—SA


它是继承但隐藏的,请参阅此 Stack Overflow的答案问题:操作员和未在C ++中继承的函数? [ ^ ]。
It is inherited but hidden, see the answer to this Stack Overflow question: "operator= and functions that are not inherited in C++?"[^].


这篇关于如何继承“operator =”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆