假设我们在类z
中有变量A
,它存储两个数字的加法,而变量w
在类B
中存储两个数字的减法,我们创建派生类D
- 我们是否可以将z
和w
中存储的这些值带到派生类D
,以便我们可以将这些数字相乘?
代码看起来像这样:
#include <iostream>
using namespace std;
class c1
{
int x, y;
public:
void getdata1(int a, int b)
{
x = a;
y = b;
}
void add1()
{
int z = x + y;
cout << "the sum is " << z << endl;
}
};
class c2
{
int x, y;
public:
void getdata2(int a, int b)
{
x = a;
y = b;
}
void sub1()
{
int w = x - y;
cout << "the sum is " << w << endl;
}
};
class D: public c1, public c2
{
/////////////////////////////////////////////////////////////////////////////////////
public:
void display()
{
cout << "the product is s" << z + w; // something like this
}
};
///////////////////////////////////////////////////////////////////////////////////////
int main()
{
D obj1;
obj1.getdata1(10, 5);
obj1.getdata2(10, 5);
obj1.add1();
obj1.sub1();
obj1.display();
return 0;
}
答案 0 :(得分:1)
您可能需要以下内容:
#include <iostream>
class c1
{
int x,y;
public:
c1(int a, int b) : x(a), y(b) {}
int sum() const { return x + y; }
};
class c2
{
int x,y;
public:
c2(int a, int b) : x(a), y(b) {}
int sub() const { return x - y; }
};
class D: public c1, public c2
{
public:
D(int a, int b) : c1(a, b), c2(a, b) {}
int foo() const { return sum() * sub(); }
};
int main(){
D obj(10, 5);
std::cout << "the sum is " << obj.sum() << std::endl;
std::cout << "the sub is " << obj.sub() << std::endl;
std::cout << "the product is " << obj.foo() << std::endl;
}
答案 1 :(得分:0)
首先尝试处理问题的格式化,这里我假设您需要代码来增加这两个变量(z和w)。
#include using namespace std;
int x,y,z,w;
class c1{
int x,y;
public:void getdata1(int a, int b){
x=a;
y=b;
}
void add1()
{
int z=x+y;
cout<<"the sum is "<<z<<endl;
return z ;
}
}
class c2 {
int x,y;
public:void getdata2(int a, int b){
x=a;
y=b;
}
void sub1()
{
int w=x-y;
cout<<"the sum is "<<w<<endl;
return w ;
}
}
class D: public c1,public c2
{
public:void multiply(int a, int b)
{
cout<<"the multiplication is "<<z*w<<endl;
}
public static int main(){
D obj1;
obj1.getdata1(10,5);
obj1.getdata2(10,5);
int a = obj1.add1();
int b = obj1.sub1();
obj1.display();
obj1.multiply(a,b)
return 0;
}
希望这是你期待的解决方案。