[英]How to pass objects as arguments?
我在這里更改了代碼,所有變量都必須保持私有,並且需要使用友元函數。 這里有兩個類 A 和 B,我應該接受 5 個數字(void enter())。函數 average 是能夠訪問所有變量並給出平均值。 我知道目前這條線
obj2.average(a,b,c,d,e);
由於變量不可訪問,會出現錯誤,所以我的問題是,如何在最后一行傳遞變量?
#include<iostream.h>
#include<conio.h>
class A
{
int a;
int b;
public:
friend class B;
int enter1()
{
cout<<"enter the value of a and b"<<endl;
cin>>a>>b;
return(a,b);
}
};
class B
{
int c;
int d;
int e;
public:
void average(int a, int b, int c, int d, int e)
{
float avg;
avg=((a+b+c+d+e)/5);
cout<<"average is "<<avg<<endl;
}
int enter()
{
cout<<"enter the value of c,d,e"<<endl;
cin>>c>>d>>e;
return(c,d,e);
}
};
void main()
{
A obj1;
B obj2;
obj1.enter1();
obj2.enter();
obj2.average(obj1.a,obj1.b,obj2.c,obj2.d,obj2.e);
}
這里有兩個類 A 和 B,我應該接受 5 個數字(void enter())。
顯示的兩個類有兩個成員函數( enter1
和enter
),都返回一個int
(而不是 beeing void
,如果我理解了問題陳述),但可能是“錯誤”的。
int enter()
{
cout << "enter the value of c,d,e" << endl;
cin >> c >> d >> e;
// The variable c, d and e here, are the private members of class B
// If we assume that all the values are correctly extracted from the input stream
// (we shouldn't, but for the sake of simplicity let's do it), those member variables
// are now set and there's no need to "return" them.
return (c,d,e);
// ^^^^^^^ The ',' here, is the comma operator(1).
// This is equivalent to
// return e;
}
所有變量都必須保持私有,並且必須使用友元函數。
在發布的代碼段中,整個類B
被聲明為類A
friend
,而不僅僅是一些函數。 這可能是完成任務的一種方式,但它似乎不能滿足要求。
計算平均值的函數被聲明為B
類的公共成員
void average(int a, int b, int c, int d, int e)
{
float avg;
avg = ((a + b + c + d + e) / 5);
// ^ This is an INTEGER division, beeing the result of
// the sum and the literal 5 both integral types, it produces a TRUNCATED integer result
// which is only after converted to a float.
// ...
}
它(錯誤地)像這樣在main
調用
obj2.average(obj1.a, obj1.b, obj2.c, obj2.d, obj2.e);
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Those are all PRIVATE members,
// invisible from 'main'
如何將對象作為參數傳遞?
滿足所有要求的一種方法可能是將average
聲明為自由函數,兩個類的朋友(可以訪問它們的私有成員),期望兩個 const 類型的參數引用類 A 和 B。
這是一個可能的實現,不一定是最好的設計。
(1) 內置逗號運算符
您不能訪問主函數中的成員變量,因為它們是私有的。 您可以將第一個實例作為參數發送給方法,然后在方法內部使用 A 類成員變量。
#include<iostream>
using std::cin;
using std::cout;
using std::endl;
class A
{
int a;
int b;
public:
friend class B;
int enter1()
{
cout<<"enter the value of a and b"<<endl;
cin>>a>>b;
return(a,b);
}
};
class B
{
int c;
int d;
int e;
public:
void average(A obj)
{
float avg;
avg=((obj.a+obj.b+c+d+e)/5);
cout<<"average is "<<avg<<endl;
}
int enter()
{
cout<<"enter the value of c,d,e"<<endl;
cin>>c>>d>>e;
return(c,d,e);
}
};
int main()
{
A obj1;
B obj2;
obj1.enter1();
obj2.enter();
obj2.average(obj1);
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.