两个问题

AbnerChai 2007-04-19 12:57:35
1) 基类Base有个构造函数Base(char *pstr){},根据一个字符串形成一个对象,派生类Derived也有个构造函数Derived(char *pstr),也根据一个字符串形成一个对象,但派生类构造函数需要的字符串pstr的前半部分是给派生类自己用的(初始化派生类自己特有的变量,pstr的后半部分可以用来显示调用基类的构造函数,作为输入,请问怎么写这个派生类的构造函数?

2)基类Base重载了std::ostream& operator <<(std::ostream& os, Base& b);
用于用自己的格式输出Base,派生类Derived也重载了std::ostream& operator <<(std::ostream& os, Derived& d);也用于用派生类的格式输出Derived,但派生类的输出是在基类输出的后面在把派生类特有的信息输出来。请问在派生类的
<<重载函数中怎么调用基类的<<把基类的部分先输出出来?

谢谢!
...全文
182 10 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
yutaooo 2007-04-19
  • 打赏
  • 举报
回复
我的命令行:

cl -EHsc -I\yutao\workspace\boost_1_33_1 test4.cpp

\yutao\workspace\boost_1_33_1 是我boost的目录
test4.cpp是上帖的文件
yutaooo 2007-04-19
  • 打赏
  • 举报
回复
我写了一个。


#include <iostream>
#include <utility> // for std::pair std::make_pair
#include <cstdlib> // for EXIT_SUCCESS
#include <boost/lexical_cast.hpp> // for boost::lexical_cast

namespace test {
// cast 方法实现依据std::string生成指定的对象
int cast(std::string const & s) {
return boost::lexical_cast<int>(s);
}

std::pair<std::string, std::string> divid(std::string const & s) {
// 这里实现分割字符的语意, 我就不实现了。用临时变量代替
std::pair<std::string, std::string> str2 = std::make_pair("1", "2");
return str2;
}

class base {
friend std::ostream & operator << (std::ostream & os, base const & b);
public:
base(std::string const & s)
: value_(cast(s)) { }
private:
int value_;
};

std::ostream & operator << (std::ostream & os, base const & b) {
os << "base format: " << b.value_;
return os;
}

class derived : public base {
friend std::ostream & operator << (std::ostream & os, derived const & d);
public:
derived(std::string const & s)
: base(divid(s).first),
value_(cast(divid(s).second)) { }
private:
int value_;
};

std::ostream & operator << (std::ostream & os, derived const & d) {
os << "derived format: ";
os << static_cast<base>(d) << ' ';
os << d.value_;
return os;
}
}

int main() {
test::derived d("asdjfka");

std::cout << d << std::endl;
}
taodm 2007-04-19
  • 打赏
  • 举报
回复
当然是先在派生类里调父类的print啦。
Base::print(...);
类名限定都没学过?C++基础知识需要补课了。
AbnerChai 2007-04-19
  • 打赏
  • 举报
回复
派生类的虚函数还是没法重用父类的print()先把父类Base的一些特殊的东西输出?
难道先在派生类里调用父类的print()?如何调用?

还是要在派生类里把父类的print部分重新写一篇?
taodm 2007-04-19
  • 打赏
  • 举报
回复
基类Base重载了std::ostream& operator <<(std::ostream& os, Base& b);
那么,里面应该转调一个virtual的print成员函数。
派生类直接实现print虚函数即可。
飞哥 2007-04-19
  • 打赏
  • 举报
回复
虚函数?
AbnerChai 2007-04-19
  • 打赏
  • 举报
回复
问题二有何好办法?
xiaoruili 2007-04-19
  • 打赏
  • 举报
回复
同意wanfustudio(雁南飞:知识之败,慕虚名而不务潜修也) 的说法
iambic 2007-04-19
  • 打赏
  • 举报
回复
考虑使用组合而不是继承。看不出来你有使用继承的必要。
飞哥 2007-04-19
  • 打赏
  • 举报
回复
呵呵,你这前半部分,后半部分,搞两个参数好了

65,189

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧