作者hunandy14 (Charlott.HonG)
看板C_and_CPP
标题[问题] 继承後 opretor+ 型别转换问题
时间Sat Mar 18 16:55:42 2017
参考代码:
https://goo.gl/jxbkwE
我建了一个 template Arr 的类别目的要集合 +- 运算的代码写在同一处
父类别(operator写在这里)
Arr<int> a{0, 1, 2};
子类别
Arr_int b{0, 1, 2};
当我使用 b=b+b;
的时候因为 b+b 返还的类别是 Arr 造成了
Arr_int = Arr; 的窘况,然後就找不到那个运算子了
这能怎麽处理~
我有试着将他向下转换不行呢QuQ 为什麽
b = dynamic_cast<Arr_int>(b+b);
有什麽比较好的作法吗
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 218.166.134.30
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/C_and_CPP/M.1489827345.A.FB2.html
1F:推 loveflames: Arr<T1> operator+会造成slicing 03/18 17:18
2F:→ loveflames: 然後没有虚函数不能用dynamic_cast向下转型 03/18 17:19
3F:推 loveflames: operator+必须设计成值返回,看你要不要在子类重写一 03/18 17:22
4F:→ loveflames: 个 03/18 17:22
5F:推 loveflames: 啊,上面讲的是写一个子类版的operator+,不是写在子 03/18 17:37
6F:→ loveflames: 类里面 03/18 17:37
多写一个
Arr_int operator+(Arr_int const &lhs, Arr_int const &rhs){
return Arr_int(lhs) += rhs;
}
会出现错误呢~QuQ 这什麽意思
inhereit.hpp: In function 'Arr_int operator+(const Arr_int&, const Arr_int&)':
inhereit.hpp:56:25: error: could not convert 'Arr_int((* &
lhs)).Arr_int::<anonymous>.Arr<T>::operator+=<int>((&
rhs)->Arr_int::<anonymous>)' from 'Arr<int>' to 'Arr_int'
return Arr_int(lhs) += rhs;
~~~~~~~~~~~~~^~~~~~
※ 编辑: hunandy14 (218.166.134.30), 03/18/2017 18:09:01
7F:推 loveflames: operator+=返回型态是父类的参考 03/18 19:01
8F:推 loveflames: 有空参考exceptional c++ item 20 03/18 19:51
9F:→ loveflames: 这会是你要的 03/18 19:51
好的~
※ 编辑: hunandy14 (218.166.134.30), 03/19/2017 12:41:36