我认为继承的类构造函数不起作用。调用时调用的变量数据不正确

时间:2013-11-21 20:12:47

标签: c++ class inheritance

感谢任何提前阅读此内容的人。

当我调用函数(report)打印出子类的所有成员时,字段要么带有奇怪的字符,要么是奇怪的字符,而有时是非字符变量中的0。

这样做的目的是证明我可以创建一个有功能的继承类。

我想我可能只是因为我是编程新手而没有做正确的事情。尽量不要太过努力。 :)

这就是我所拥有的:

// classes

// base class
class Cd 
{
private:
protected:
    char performers[50];
    char label[60];
    int selections; 
    double playtime; 
public:
    Cd(char * s1, char * s2, int n, double x);
    Cd(const Cd & d);
    Cd();
    ~Cd();
    void Report() const; // reports all CD data
    Cd & operator=(const Cd & d);
};

class Classic : public Cd  // Sub-class
{
public:
Classic();
Classic(char * s0, char * s1,  char * s2, int n, double x);
~Classic();
Classic & operator=(const Classic & c);
void Report() const;

private:
char primaryWork[50];
};

//方法

inline Cd::Cd(char * s1,char * s2, int n, double x)  // base class constructor
{
    std::strncpy(performers, s1, 49);
    std::strncpy(label, s2, 59);
    selections = n;
    playtime = x;
}

inline Classic::Classic(char * s0, char * s1,  char * s2, int n, double x) 
{
    std::strncpy(performers, s1, 41);
    std::strncpy(label, s2, 59);
    selections = n;
    playtime = x;
    std::strncpy(primaryWork, s0, 49);
}
是的,我知道这几乎看起来我不会重复使用任何代码。这是我最接近它的工作。我也试过(除了其他变种):

Classic(char * s0, const Cd & c); // constructor declaration

inline Classic::Classic(char * s0, const Cd & c) : Cd(c)  // constructor definition
{
    std::strncpy(primaryWork, s0, 49);
}

但是我得到了“没有重载的函数需要5个参数。 无论如何,这是main()代码:

Classic c2("Piano Sonata in B flat, Fantasia in C",
 "698 C++ PRIMER PLUS, FIFTH EDITION Alfred Brendel", "Philips", 2, 57.17);

c2.Report();

报告功能的定义。

inline void Classic::Report() const
{
cout << endl << "Performers: " << performers << endl;
cout << "Label: " << label << endl;
cout << "Number of Selections: " << selections << endl;
cout << "Playtime: " << playtime << endl;
cout << "Primary Work: " << primaryWork << endl;
}

这只是第一部分,但它已经失败了。

请欢迎任何意见。而且,再次感谢你。

1 个答案:

答案 0 :(得分:2)

你必须告诉C ++使用哪个构造函数,否则它将默认使用默认构造函数:

inline Classic::Classic(char * s0, char * s1,  char * s2, int n, double x) :
    Cd(s1,s2,n,x)
{
   std::strncpy(primaryWork, s0, 49);
}

应该做你想做的事