具有const数据成员的对象作为类的成员

时间:2015-10-11 22:49:06

标签: c++ object

因此,我正在尝试编写一个名为本科的课程,该课程将Phone类的对象作为参数。但是,phone类使用名为msg的const数据成员。由于手机类中的const数据成员,这将无法编译。我如何解决它?任何帮助将不胜感激!

//下面是我的Phone类的默认构造函数,它使用const数据成员msg

Phone::Phone():msg(10){ //intialize const data member

    areacode = 999;

    exchange = 999;

    line = 9999;
}

//这是我的构造函数,它将对象作为参数

Undergraduate::Undergraduate(Name sname, Date bday, Program sprogram, Phone sphone, char g, string s, int c, double G, int gdyr, string term){

    name = sname;
    date = bday;
    pgm = sprogram;
    phone = sphone;

    gender = g;
    status = s;
    credit = c;
    gpa = G;
    gradyear = gdyr;
    gradterm = term;
}

1 个答案:

答案 0 :(得分:0)

我认为这里的问题可能是你在说phone = sphone;这将需要更改const成员。您可以使用本科课程中的初始化列表进行初始化。

Undergraduate::Undergraduate(Name sname, Date bday, Program sprogram, Phone sphone, char g, string s, int c, double G, int gdyr, string term)
: phone(sphone)
{

    name = sname;
    date = bday;
    pgm = sprogram;

    gender = g;
    status = s;
    credit = c;
    gpa = G;
    gradyear = gdyr;
    gradterm = term;
}