2013-03-01 133 views
2

为什么这个代码:为什么重载的赋值操作符不会被继承?

class X { 
public: 
    X& operator=(int p) { 
     return *this; 
    } 
    X& operator+(int p) { 
     return *this; 
    } 
}; 

class Y : public X { }; 

int main() { 
    X x; 
    Y y; 
    x + 2; 
    y + 3; 
    x = 2; 
    y = 3; 
} 

给错误:

prog.cpp: In function ‘int main()’: 
prog.cpp:14:9: error: no match for ‘operator=’ in ‘y = 3’ 
prog.cpp:14:9: note: candidates are: 
prog.cpp:8:7: note: Y& Y::operator=(const Y&) 
prog.cpp:8:7: note: no known conversion for argument 1 from ‘int’ to ‘const Y&’ 
prog.cpp:8:7: note: Y& Y::operator=(Y&&) 
prog.cpp:8:7: note: no known conversion for argument 1 from ‘int’ to ‘Y&&’ 

为什么+运营商继承,但=运营商呢?

+2

回答你的问题是[这里](http://stackoverflow.com/questions/12009865/operator-和函数 - 不是继承在 - c) – 2013-03-01 13:36:56

回答

9

Y包含隐式声明的赋值运算符,它隐藏了在基类中声明的运算符。通常,在派生类中声明一个函数会隐藏在基类中声明的具有相同名称的任何函数。

如果你想既提供Y,使用using声明:

class Y : public X { 
public: 
    using X::operator=; 
}; 
+0

如果类“Y”需要“扩展”运算符'=',即比父类中的return * this做更多的事情? – Ignorant 2015-12-07 17:35:07

+0

然后你自己重写它,就像你最初做的那样,不要使用继承。我个人发现使用虚拟操作符过载并不总是最好的 – Curious 2016-01-01 00:00:23

0

如果未声明编译器自动生成的方法,则会忘记它们。作业是其中之一。

+0

为什么自动生成删除我的定义,当他们有不同的签名? – Eric 2013-03-01 13:38:36

+0

@Eric:它不会删除它,它会隐藏它。 – 2013-03-01 13:38:49

+0

@AndyProwl:同样的问题然后:为什么它隐藏它,当签名不冲突? – Eric 2013-03-01 13:39:40