首页 > 试题广场 >

有以下程序 #include ...

[不定项选择题]
有以下程序
#include<iostream> 
using namespace std;

class complex {
	int real;
	int imag;
public:
	complex(int r = 0, int i = 0) {
		real = r;
		imag = i;
	}
	_________________________________
};

void add(complex& a, complex& b) {
	int r = a.real + b.real;
	int i = a.imag + b.imag;
	cout << r << "+" << i << "i" << endl;
}

int  main() {
	complex x(1, 2), y(3, 4), z;
	add(x, y);
}


程序的输出结果为4+6i,请为横线处选择合适的程序        (      )
  • friend complex add(complex &a,complex & b) ;
  • friend complex add(complex &,complex &) ;
  • complex add(complex &a,complex & b) ;
  • complex add(complex ,complex ) ;
z=add(x,y);操作说明add函数不是类的成员函数。定义为友元函数,则可以直接函数内对类成员变量访问。并且声明友元函数时,形列表里可以只加类型,也可类型和对应对象。
发表于 2020-09-25 21:12:58 回复(3)
应该是friend void add吧 friend complex add 是会报错的 返回类型都对不上
发表于 2022-02-10 15:34:54 回复(4)
?
发表于 2020-09-21 16:52:52 回复(0)
真的有必要声明为friend么??
发表于 2021-04-15 22:50:08 回复(5)
什么破题
编辑于 2023-12-09 20:49:02 回复(0)
关于这里为什么不能定义类中函数,我的看法是程序在调用时是直接使用的函数名,而不是通过对象来调用,也就是z.add(x,y)
发表于 2023-08-25 16:36:42 回复(0)
声明的友元函数的返回值类型和调用该函数的返回类型可以不相同
发表于 2023-07-23 21:17:39 回复(0)
题目和答案对不上
发表于 2022-11-25 23:08:24 回复(0)