关于类的定义回头补充,现在先直接上代码**
#include
#include
#include
#include
#include
//#include
#include
#include
using namespace std;
#pragma warning(disable:4996)//禁用_s报错
class cy
{
//以下为私有成员
int a;
double b;
char c;
string d;
public:
//以下为公有成员
cy()//默认构造函数,给私有成员赋值
{
a = 1; b = 2.2; c = 'A'; d = "abc";
}
//无实参访问私有成员变量
int zx() { return a; }
double fdx() { return b; }
char zfx() { return c; }
string zfcx(){ return d; }
//在类外定义,因不需要返回值,故函数类型为void(空)
void zx(int q);
void fdx(double w);
void zfx(char e);
void zfcx(string r);
// 若在需要在类中定义,代码为void zx(int q){a = q;}
//但是一般不这做,类中代码太长了,可以在类的外面定义后将函数块折叠,更加美观!
};
//利用类里的成员函数给私有成员变量赋值
void cy::zx(int q)//格式为函数类型(如void)+空格+类名+::(二元作用域解析运算符)+函数名字+(变量类型名 形参变量)
{
a = q;
}
void cy::fdx(double w)
{
b = w;
}
void cy::zfx(char e)
{
c = e;
}
void cy::zfcx(string r)
{
d = r;
}
int main()
{
int q;
double w;
char e;
string r;
cin >> q >> w >> e >> r;
cy s1, s2;//定义名为s1和s2的类
cout << s1.zx() << " " << s1.fdx() << " " << s1.zfx() << " " << s1.zfcx() << endl;
//输出类s1中的私有成员变量的值,因为无参数,故调用cy类中的函数,返回私有函数的值
s2.zx(q); s2.fdx(w); s2.zfx(e); s2.zfcx(r);
//调用类s2中的函数给私有成员赋值。
cout << s2.zx() << " " << s2.fdx() << " " << s2.zfx() << " " << s2.zfcx() << endl;
//给类s2的私有成员赋值后,调用cy类中的函数,返回私有函数的值;
s1 = s2;//将类s2中所有的成员变量赋值给类s1
cout<< s1.zx() << " " << s1.fdx() << " " << s1.zfx() << " " << s1.zfcx() << endl;
//给类s1的私有成员赋值后,调用cy类中的函数,返回私有函数的值;
}
此时输入 :
10 22 A ABC
输出:
1 2.2 A abc
10 22 A ABC
10 22 A ABC