samba添加账号:c++的一个程序问题

来源:百度文库 编辑:高考问答 时间:2024/04/28 01:24:43
//4-13
#include<iostream.h>
#include"10.h"
void main()
{
int i;

cout<<"Please enter the i:i=";
cin>>i;
X x(i);
Y y(x);
Z z(x);
cout<<"y.g(i)="<<y.g(i)<<endl;
cout<<"z.f(i)="<<z.f(i)<<endl;
cout<<"h()"<<h(x)<<endl;
}
//4-13.h
#include<iostream.h>
extern i;
class X
{
private:
int i;
public:
X(int a){i=a;}
friend class Z;
friend class Y;
friend int h(X &x);
};
class Y
{
private:
X x;
public:
Y(X x){};
int g(int i)
{return i+=1;}
};
class Z
{
private:
X x;
public:
Z(X x){};
int f(int i){return i+=5;}
};
int h(X &x)
{return x.i+=10;}
帮我看看,如何对class Y和class Z定义初值?

你可以在头文件中把class X的构造函数都给初值
修改如下:
//test.cpp
#include<iostream.h>
#include"test.h"
void main()
{
int i;
cout << "Please enter the i:i=";
cin >> i;
X x; // 修改的地方
Y y(x);
Z z(x);
cout << "y.g(i)=" << y.g(i) << endl;
cout << "z.f(i)=" << z.f(i) << endl;
cout << "h()" << h(x) << endl;
}
//test.h
#include<iostream.h>

extern i;

class X
{
private:
int i;
public:
X(int a = 1 ){i=a;} // 修改的地方
friend class Z;
friend class Y;
friend int h(X &x);
};
class Y
{
private:
X x;
public:
Y(X x){}
int g(int i){return i+=1;} // 该i是输入的i
/* 若想使用X类的i,应该代码为:
* int g() { retrun x.i++; }
*/
};
class Z
{
private:
X x;
public:
Z(X x){}
int f(int i){return i+=5;} // 该i是输入的i
/* 若想使用X类的i,应该代码为:
* int f() { retrun x.i+ = 5; }
*/
};
int h(X &x)
{
return x.i+=10; // 该i是类X中的默认值1
}

当运行该程序时,输入2,回车,结果为:
Please enter the i:i=2
y.g(i)=3
z.f(i)=7
h()11