提前感谢所有阅读本文的人。
当我调用函数(报告)打印出子类的所有成员时,返回的字段要么带有奇怪的字符,要么是正确的数据,然后是奇怪的字符,有时在非字符变量中为 0。
这样做的目的是为了证明我可以制作一个功能正常的继承类。
我想我可能只是没有正确地做一些事情,因为我是编程新手。尽量不要用力捂脸。 :)
这是我所拥有的:
//类
// 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;
}
这只是第一部分,但到那时它已经失败了。
欢迎任何输入。再次感谢您。
最佳答案
你必须告诉 C++ 使用哪个构造函数,否则它将默认使用默认构造函数:
inline Classic::Classic(char * s0, char * s1, char * s2, int n, double x) :
Cd(s1,s2,n,x)
{
std::strncpy(primaryWork, s0, 49);
}
做自己想做的事
关于c++ - 我认为继承类构造函数不起作用。调用时调用的变量中的数据不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20130978/