我一直在使用 Turbo C++ 编写关于多重继承的代码,代码的目的是只获取输入并在控制台打印输入。我最初完成了以下代码,
// Program to demonstrate multiple inheritance
#include <conio.h>
#include <iomanip.h>
#include <iostream.h>
#include <stdio.h>
#include <stdlib.h>>
#include <string.h>
class Company1
{
protected:
int productID;
char *productName;
char *CompanyName;
public:
void input_c1()
{
cout << "Provide Company 1 Details : " << endl;
cout << setw(29) << setfill('-') << "" << endl;
cout << "Enter the Product ID : ";
cin >> productID;
cout << "Enter the Product Name : ";
gets(productName);
cout << "Enter the Company Name : ";
gets(CompanyName);
}
};
class Company2
{
protected:
int productID;
char *productName;
char *CompanyName;
public:
void input_c2()
{
cout << endl << "Provide Company 2 Details : " << endl;
cout << setw(29) << setfill('-') << "" << endl;
cout << "Enter the Product ID : ";
cin >> productID;
cout << "Enter the Product Name : ";
gets(productName);
cout << "Enter the Company Name : ";
gets(CompanyName);
}
};
class SuperMarket : public Company2, public Company1
{
public:
void Company_details()
{
cout << endl << "Company 1 details : " << endl;
cout << setw(20) << setfill('-') << "" << endl;
cout << "Product ID : " << Company1::productID << endl;
cout << "Product Name : ";
print_string(Company1::productName);
cout << endl;
cout << "Company Name : ";
print_string(Company1::CompanyName);
cout << endl << endl;
cout << "Company 2 details : " << endl;
cout << setw(20) << setfill('-') << "" << endl;
cout << "Product ID : " << Company2::productID << endl;
cout << "Product Name : ";
print_string(Company2::productName);
cout << endl;
cout << "Company Name : ";
print_string(Company2::CompanyName);
}
void print_string(char *ptr)
{
for (int i = 0; i != strlen(ptr); i++)
cout << ptr[i];
}
};
void main()
{
char choice;
clrscr();
SuperMarket s;
s.input_c1();
s.input_c2();
s.Company_details();
cout << endl << "Do you want to exit ? (Y/N) : ";
cin >> choice;
if (choice == 'Y' || choice == 'y')
exit(0);
getch();
}
并在执行时得到如下输出,
But that wasn't the output which is expected because the Company Name of Company1 is dklm instead it was expected to be def. I further on tried to rectify it and made the derivation type of Company1 as virtual public and this resulted in correct output. I heard that virtual is used mostly in the cases of Diamond problem. Despite not being a Diamond problem it has resulted in the correct output. Can anyone please explain why did I get such kind of wrong output in the mentioned program and how did the virtual made to work the program properly in this case ?
指针productName
和CompanyName
未初始化,因此您不能使用它们,就好像它们指向某些字符的有效存储一样。你应该只使用std::string
而不是char*
指针,以避免这个问题和许多其他问题。
尽管 Turbo C++ 没有std::string
,但如果您必须使用该编译器,也许您可以为它找到一个好的字符串类。我对此无能为力,因为此时 Turbo C++ 甚至都算不上 C++。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句