【发布时间】:2014-12-14 20:33:32
【问题描述】:
我是 C++ 初学者,遇到以下问题。我有三个班级:祖父母,父母和孩子。思路是这样的
#include <iostream>
#include <stdlib.h>
#include <string.h>
class Book
{ protected:
long int number;
char author[25];
int year;
bool lent;
void setLent(bool x);
bool getLent();
public:
Book(long int n, char a[25], int j, bool x);
long int getNr();
int getYear();
void print();
};
class UBook: public Book
{ protected:
int categ;
char country[15];
private:
int for_age;
public:
UBook(int t, int k, char l[15]);
void setAge(int a);
int getAge();
};
class PicBook: public UBook
{ private:
static const int for_age=6;
public:
PicBook(long int n, char a[25], int j,int k, char l[15]);
};
Book::Book(long int n, char a[25], int j, bool x)
{number=n;
strncpy(author, a, 25);
year=j;
lent=x;}
long int Book::getNr()
{return number; }
int Book::getYear()
{return year;}
void Book::setLent(bool x)
{lent=x;}
bool Book::getLent()
{return lent;}
void Book::print()
{
std::cout << "Booknumber: " << number << std::endl;
std::cout << "Author: " << author << std::endl;
std::cout << "Year: " << year << std::endl;
if (lent==0)
std::cout << "Lentiehen [ja/nein]: nein" << std::endl;
else
std::cout << "Lentiehen [ja/nein]: ja" << std::endl;
}
UBook::UBook(int t, int k, char l[15]): Book(number, author, year, lent)
{for_age=t;
categ=k;
strncpy(country, l, 15);
}
void UBook::setAge(int a)
{for_age = a;}
int UBook::getAge()
{return for_age;}
PicBook::PicBook(long int n, char a[25], int j,int k, char l[15]): UBook(for_age, categ, country)
{
std::cout << "Booknumber: " << number << std::endl;
std::cout << "Author: " << author << std::endl;
std::cout << "Year: " << year << std::endl;
std::cout << "For age: " << for_age << std::endl;
std::cout << "Categorie: " << categ << " [Bildband]" << std::endl;
std::cout << "Country: " << country << std::endl;
}
int main()
{
PicBook somebook(356780, "test", 2010, 4, "France");
system("pause");
return 0;
}
但是,如果我在“child”中进行测试输出,则会出现一些奇怪的输出:
Book Nr: 4283296
Author: ð■(
Year: 1988844484
For age: 6 /*(the only correct output)*/
Categorie: 2686760 [Bildband]
Country: ♠\A
Press any key to continue . . .
所以我的参数没有正确传递。前 3 个参数是祖父类的成员,后两个是父类的成员。我认为“孩子”中的构造函数可能存在问题。
提前感谢您的帮助!
【问题讨论】:
-
child::other隐藏成员变量parent::other。child::other在您将其传递给parent时未初始化,从而导致未定义的行为。将grandparent::test传递给grandparent的构造函数也是如此。帮自己一个忙,获得good book on C++。 -
这不是 C++ 代码。
Class是什么?你的意思是class?类声明也需要以;结束。如果您正在寻求帮助,请复制并粘贴有问题的代码; 不要重新输入。 -
那么可能的解决方案是什么?对不起...我是真正的初学者
-
child用other初始化parent,而不是用a或b。child从不使用a或b,因此从不使用1和6应该不是什么秘密。 -
我按要求添加了真实代码
标签: c++ parameter-passing parent grandchild