派生类中的C赋值运算符

前端之家收集整理的这篇文章主要介绍了派生类中的C赋值运算符前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
参见英文答案 > operator= and functions that are not inherited in C++?3个
我不太明白为什么对于赋值,派生类不会调用基类的相应运算符,如果它自己不存在的话.看看代码
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. class A{
  5. protected:
  6. void myWrite(){
  7. cout << " Base " <<endl;
  8. }
  9. public:
  10. double x,y;
  11. A(): x{0},y{0}{};
  12. virtual A & operator=(double g){x=g;y=g;return *this;}
  13. virtual ~A(){};
  14. virtual void doneit(){myWrite();}
  15. };
  16.  
  17.  
  18. class B: public A{
  19. protected:
  20. public:
  21. B():A(){};
  22. virtual ~B(){};
  23. virtual void doneit(){myWrite();}
  24. };
  25.  
  26. int main() {
  27. A jj;
  28. B pp;
  29.  
  30. pp=0.0;
  31. return 0;
  32. }

因为它是代码不编译.当然,如果我为B定义一个“运算符=”与A的相同,那么一切正常,但是为什么默认情况下不调用B“operator =”如果未定义派生类中的那个?你能帮忙解释一下这个问题吗?

gcc编译器说../src/tito.cpp:40:4:错误:没有可行的重载’=’
PP = 0.0;
~~ ^ ~~~
../src/tito.cpp:28:7:注意:候选函数(隐式复制赋值运算符)不可行:第一个参数没有从’double’到’const B’的已知转换
B级:公共A {
^
生成1个错误.

你能解释一下为什么它不起作用吗?

解决方法

如果您没有声明复制赋值运算符,编译器将为您声明一个.所以你的B级看起来很像:
  1. class B : public A {
  2. public:
  3. // explicit
  4. B();
  5. virtual ~B();
  6. virtual void doneit();
  7.  
  8. // implicit
  9. B(const B&);
  10. B& operator=(const B&);
  11. };

隐式复制赋值运算符隐藏了您编写的A :: operator =(double),因此它是名称查找将找到的唯一候选者.当然,它不是一个可行的候选者,因为double不能转换为B,因此错误.

要使用A :: operator =(double)运算符,必​​须将其明确地引入范围:

  1. using A::operator=;

但是那时你不会分配任何B部分.所以最好更明确一点:

  1. B& operator=(double g) {
  2. // B stuff here
  3.  
  4. // A stuff
  5. A::operator=(g);
  6.  
  7. return *this;
  8. }

猜你在找的C&C++相关文章