注册 登录
编程论坛 C++教室

又是关于类的。

XIAO荣 发布于 2009-08-17 16:17, 806 次点击
请帮忙解释下注释的那一条语句,就一条,非常感谢 。
单冒号的作用...

#include<iostream.h>
#include<string.h>
const int LEN=50;
class Station
{
protected:
    char from_station[LEN];
    char to_station[LEN];
public:
    Station(char fs[],char ts[])
    {
        strcpy(from_station,fs);
        strcpy(to_station,ts);
    }
    void input_value()
    {
        cout<<"Enter from station:"<<endl;
        cin>>from_station;
        cout<<"Enter to station:"<<endl;
        cin>>to_station;
    }
    void display()
    {
        cout<<"Going from "<<from_station<<"station to "<<to_station<<" station";
    }
};
class Mile
{
protected:
    int mile;
public:
    Mile(int m)
    {
        mile=m;
    }
    void input_mile()
    {
        cout<<"Enter mile:";
        cin>>mile;
    }
    void display()
    {
        cout<<" is"<<mile<<" miles";
    }
};
class Price:public Station,public Mile
{
    int price;
public:
    Price(char ff[],char tt[],int mm,int pp):Station(ff,tt),Mile(mm)//就是这里,中间的冒号起什么作用?这类型的定义是什么格式来的?
    {
    price=pp;    
    }
    void getprice()
    {
        Station::input_value();
        Mile::input_mile();
        cout<<"Enter price:";
        cin>>price;
    }
    void display()
    {
        Station::display();
        Mile::display();
        cout<<" The price is "<<price<<endl;
    }
};
void main()
{
    Price A("Beijing","Xia men",1400,50);
    A.display();
}

[ 本帖最后由 XIAO荣 于 2009-8-17 16:19 编辑 ]
11 回复
#2
XIAO荣2009-08-17 16:23
Price(char ff[],char tt[],int mm,int pp):Station(ff,tt),Mile(mm)
冒号的作用是不是构造函数给后面的Station(ff,tt)和Mile(mm)赋值?
#3
jd2052009-08-17 17:01
类成员初始化。
如果你的Mile 继承了Station 类,但Station 又没有缺省的构造函数,就得在那加个冒号对成员初始化。
#4
XIAO荣2009-08-17 17:08
回复 3楼 jd205

请问,是冒号前面的东西对冒号后面的进行初始化,还是后面的对前面的进行初始化?
这程序,Mile好象和Station是两个不同的类吧,之间应该没什么关系吧?
#5
XIAO荣2009-08-18 10:39
有高手帮忙解答一下么??

[ 本帖最后由 XIAO荣 于 2009-8-18 10:55 编辑 ]
#6
王晓明2009-08-18 14:55
冒号前面的东西对冒号后面的进行初始化。
station和mile没有什么关系
#7
pangding2009-08-18 16:39
回复 4楼 XIAO荣

那个函数是派生类的构造函数。生成派生类之前,要先初始化基类。要用到基类的构造函数,这种语法可以把相应的参数传给基类,以调用相应的构造函数。

具体来说
Price(char ff[],char tt[],int mm,int pp):Station(ff,tt),Mile(mm)
这个就是把传给 Price 的 ff和tt 转传给 Station 以调用构造函数,把 mm 传给 Mile。
pp没传,是用来初始化 Price 自己的成员的。
#8
shzhj2009-08-18 17:22
派生类的构造函数要先调用基类的构造函数
:就是把参数从派生类的参数列表中传给基类
#9
shzhj2009-08-18 17:23
Station和Mile都是Price的基类
看你的Price的定义:
class Price:public Station,public Mile
#10
easycpp2009-08-18 20:06
这里有一个基本的事实:存在一个派生类对象,此时也必须存在一个基类的对象;如果不存在一个基类的对象,那么在派生类 中我们就不可能调用基类对象的方法了,所以派生类对象中蕴含着基类的对象。这个基本的事实要求,我们在构造派生类对象的时候必须去构造基类的对象;同时在 析构派生类对象的时候也要析构基类的对象。此时问题变成这个构造与析构的过程是以怎样的次序进行的?
可以看看这篇文章:http://www.
#11
XIAO荣2009-08-20 10:56
回复 7楼 pangding

懂了,谢谢喔。
#12
ly8610142009-08-20 15:45
回复 楼主 XIAO荣

建议好好看看课本
1