在此程序中,我试图在此程序中灌输混合继承,但这给出了错误的输出。我已将算术作为基类,并将add
,sub
,mul
,div
作为其派生类。
然后我使用add
,sub
,mul
,div
作为基类派生了一个类结果。我已经尝试了所有数据类型,但是所有这些数据类型都会给出错误或为零的输出。
#include "iostream"
using namespace std;
class arithmetic
{
public:
float var1,var2;
void introduce()
{
cout<<"This program will perform arithmetic on two variables"<<endl
<<"Enter the first variable: ";
cin>>var1;
cout<<"Enter the second variable: ";
cin>>var2;
}
};
class add:public arithmetic
{
protected:
float res_add;
public:
void show_add()
{
res_add=var1+var2;
cout<<"Addition of those variables gives "<<res_add<<endl;
}
};
class sub:public arithmetic
{
protected:
float res_sub;
public:
void show_sub()
{
res_sub=var1-var2;
cout<<"Subtraction of those variables gives "<<res_sub<<endl;
}
};
class mul:public arithmetic
{
protected:
float res_mul;
public:
void show_mul()
{
res_mul=var1*var2;
cout<<"Multiplication of those variables gives "<<res_mul<<endl;
}
};
class div:public arithmetic
{
protected:
float res_div;
public:
void show_div()
{
res_div=var1/var2;
cout<<"Divison of those variables gives "<<res_div<<endl;
}
};
class result:public add, public sub,public mul,public div
{
public:
void showres()
{
cout<<"Arithmetic on the given two varibales gives us the following result:"<<endl;
}
};
int main()
{
result example;
arithmetic var;
var.introduce();
example.showres();
example.show_add();
example.show_sub();
example.show_mul();
example.show_div();
return 0;
}
答案 0 :(得分:1)
您正在创建两个单独的对象var(基类对象)和example(派生类对象)。通过在示例对象中调用var.introduce()并调用方法show_add(),show_sub()等来初始化var1和var2,在示例对象var1和var2中未初始化。因此,您要调用的任何算术运算都将应用于示例对象的未初始化的var1和var2成员变量。
您不需要创建基类对象(var)。从示例中调用intruduce()方法,它将开始正常工作。
请仔细阅读以下示例代码,以了解虚拟基类的概念。
#include <iostream>
class A
{
public:
int i;
};
class B : virtual public A
{
public:
int j;
};
class C: virtual public A
{
public:
int k;
};
class D: public B, public C
{
public:
int sum;
};
int main()
{
D ob;
ob.i = 10; //unambiguous since only one copy of i is inherited.
ob.j = 20;
ob.k = 30;
ob.sum = ob.i + ob.j + ob.k;
std::cout << "Value of i is : "<< ob.i<<"\n";
std::cout << "Value of j is : "<< ob.j<<"\n";
std::cout << "Value of k is : "<< ob.k<<"\n";
std::cout << "Sum is : "<< ob.sum <<"\n";
return 0;
}
输出:
Value of i is : 10
Value of j is : 20
Value of k is : 30
Sum is : 60
答案 1 :(得分:0)
如果要避免虚拟继承并希望简单一些,请使用组合。
为此,class result
应该包含add
,sub
,mul
和div
的对象。
result
的结果代码如下:
class result:public arithmetic
{
public:
mul m;
add a;
sub s;
div d;
void assignvals()
{
m.var1 = var1; m.var2 = var2;
a.var1 = var1; a.var2 = var2;
s.var1 = var1; s.var2 = var2;
d.var1 = var1; d.var2 = var2;
}
void showres()
{
cout<<"Arithmetic on the given two variables gives us the following result:"<<endl;
}
};
main
的结果代码如下:
int main()
{
result example;
example.introduce();
example.assignvals();
example.showres();
example.a.show_add();
example.s.show_sub();
example.m.show_mul();
example.d.show_div();
return 0;
}
注意::某些编译器会抱怨将div
用作类名,因为它也是C ++中库函数的名称。因此,您将不得不更改此类的名称。