鱼C论坛

 找回密码
 立即注册
查看: 4023|回复: 4

C++ 继承机制中的构造器-带输入参数的问题;

[复制链接]
发表于 2013-2-9 16:05:12 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 licker 于 2013-2-9 16:17 编辑


#include <iostream>
#include <string>
class Animal
{
public:
std::string name;
Animal(std::string thename);
~Animal();
void eat();
void sleep();
void drool();
};
//基类;
Animal::Animal(std::string thename)
{
name = thename;
}
Animal::~Animal()
{
std::cout << "析构器!" << std::endl;
}
void Animal::eat()
{
std::cout << "I'm eating!" << std::endl;
}
void Animal::sleep()
{
std::cout << "I'm sleeping, Don't distrub me!" <<std::endl;
}
void Animal::drool()
{
std::cout << "我是男的,看到女的会流口水..." <<std::endl;
}
//Pig子类;
class Pig : public Animal
{
public:
void climb();
void eat();
Pig(std::string thename);
};
void Pig::climb()
{
std::cout << "我是一头猪,会上树!" <<std::endl;
}
void Pig::eat()
{
std::cout << name << "小猪正在吃大象!" << std::endl;
}
Pig::Pig(std::string thename):Animal(thename)
{
}
//Trutle子类;
class Turtle : public Animal
{
public:
void swim();
void eat();
Turtle(std::string thename);
};
void Turtle::swim()
{
std::cout <<"我是一只小甲鱼,看到母猪会跳到水里!"<<std::endl;
}
void Turtle::eat()
{
std::cout<< name << "正在吃大鱼!!"<<std::endl;
}
Turtle::Turtle(std::string thename):Animal(thename)
{
}

//main函数;
int main()
{
Pig pig("小甲鱼 ");
Turtle turtle("T12333 ");
//去掉红色部分,上面改为:Turtle turtle(); 编译会出错,为啥?基类定义了带参数,子类就必需要定义的吗?//


pig.eat();
turtle.eat();
pig.climb();
turtle.swim();
return 0;
}
小甲鱼最新课程 -> https://ilovefishc.com
发表于 2013-2-9 16:09:56 | 显示全部楼层
1. 子类对象包含基类部分
2. 子类对象必须调用基类的某个构造函数来初始化它的基类部分(否则它的基类部分如何初始化呢)
3. 由于基类只有带参构造函数,所以子类必须调用基类的带参构造函数来初始化其基类部分,但不是说子类的构造函数就不能无参,比如可以:
Turtle::Turtle():Animal("ppmm"){ }
小甲鱼最新课程 -> https://ilovefishc.com
 楼主| 发表于 2013-2-9 16:19:45 | 显示全部楼层

唉,真难编辑,代码无办法着色,又改回来了...现在勉强能描述问题了...
看了你的回复,还是不明白 ....我再想想..
小甲鱼最新课程 -> https://ilovefishc.com
 楼主| 发表于 2013-2-9 16:22:27 | 显示全部楼层
本帖最后由 licker 于 2013-2-9 16:25 编辑

那我只能理解成:基类带参数,子类就必需要带参数了....只要我调用了,就必需带参数....
小甲鱼最新课程 -> https://ilovefishc.com
发表于 2013-2-9 16:40:44 | 显示全部楼层
licker 发表于 2013-2-9 16:22
那我只能理解成:基类带参数,子类就必需要带参数了....只要我调用了,就必需带参数....
  1. #include <iostream>
  2. using namespace std;

  3. class Base{
  4. public:
  5.         Base(int n):data(n){}
  6.         int getData()const{ return data; }
  7. private:
  8.         int data;
  9. };

  10. class Derived:public Base{
  11. public:
  12.         Derived():Base(5){}
  13.         void print()const{ cout<<"Derived's data is:"<<getData()<<endl; }
  14. };

  15. int main(){
  16.         Derived d;
  17.         d.print();
  18. }
复制代码
自己看代码吧:
小甲鱼最新课程 -> https://ilovefishc.com
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-8-8 10:26

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表