我一直在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();
}
执行后得到如下输出
但这不是预期的输出,因为 Company1 的 Company Name 为 dklm ,而预期为 def 。我进一步尝试纠正它,并将 Company1 的派生类型设置为虚拟公共,这导致正确的输出。听说虚拟主要用于钻石问题。尽管不是 Diamond问题,但它可以产生正确的输出。谁能解释为什么我在提到的程序中得到了这样的错误输出?在这种情况下,虚拟机如何使程序正常工作?