设为首页 加入收藏

TOP

C++面向对象程序设计之C++的初步知识(二)
2019-07-10 18:11:09 】 浏览:353
Tags:面向 对象 程序设计 初步 知识
tud1的dispaly函数
    stud2.dispaly();                    //调用对象stud2的dispaly函数
    return 0;
}


包含类的C++程序


程序分析:


1.3 C++对C的扩充


1.3.1 C++的输入输出


如果要指定输出所占列数,可以用控制符setw进行设置,如setw(5)的作用是为其后面一个输出项预留5列的空间,如果输出数据项的长度不足5列,则数据向右对齐,若超过5列则按实际长度输出。如下所示:


#include<iomanip>
#include<iostream>
using namespace std;
int main()
{
float a=3.45;
int b=5;
char c='A';
//cout << "a="<<a<<","<< "b="<<b<<","<< "c="<<c<<endl;
//cout << "a="<<setw(6)<<a<<","<< "b="<<setw(6)<<b<<","<< "c="<<setw(6)<<c<<endl;
cout << "a="<<a<<endl;
cout << "b="<<b<<endl;
cout << "c="<<c<<endl;
cout << "a="<<setw(6)<<a<<endl;
cout << "b="<<setw(6)<<b<<endl;
cout << "c="<<setw(6)<<c<<endl;
system("pause");
return 0;
}


运行结果:


C++面向对象程序设计之C++的初步知识


代码分析:


1.3.2 用const定义常变量


实际上,只是在预编译时进行字符置换,把程序中出现的字符串PI全部置换成3.14159.在预编译之后,程序中不再有PI这个标识符。PI不是变量,没有类型,不占用存储单元,而且容易出错。如下:


#include<iostream>
using namespace std;
int main()
{
int a=1;int b =2;
#define PI 3.14159
#define R a+b
cout <<PI*R*R<<endl;


system("pause");
return 0;
}


输出结果为 7.14159,即输出的并不是3.14159*(a+b)*(a+b),而是3.14159*a+b*a+b。程序因此常常出错。


C++提供了用const定义常变量的方法,如下:


#include<iostream>
using namespace std;
int main()
{
int a=1;int b =2;
const float PI=3.14159;
//#define R a+b;    //此句有错误
const R=a+b;
cout <<PI*R*R<<endl;


system("pause");
return 0;
}


输出结果为28.2743 。


程序分析:


1.3.3 函数原型声明


C++中,强制要求在函数调用之前必须对所调用的函数做函数原型声明。即:int max(int x, int y);  //max函数原型声明。


参数表中一般包括参数类型和参数名,也可以只包括参数类型而不包括参数名,如下两种写法等价:


int max(int x, int y);    //等价于下面


int max(int , int);


1.3.4 函数的重载


插入,提取运算符"<<",">>",本来是C和C++位运算中的左移运算符和右移运算符;重载其实就是一物多用。


C++允许在同一作用于中用同一函数名定义多个函数,这些函数的参数个数和参数类型不相同,这些同名函数用来实现不同的功能。这就是函数的重载,即一个函数名多用。


#include<iostream>
using namespace std;
int max(int a,int b, int c)            //求三个整数中的最大者
{
if (b>a) a=b;
if (c>a) a=c;
return a;
}


float max(float a,float b, float c)            //求三个整数中的最大者
{
if (b>a) a=b;
if (c>a) a=c;
return a;
}


long max(long a,long b, long c)            //求三个整数中的最大者
{
if (b>a) a=b;
if (c>a) a=c;
return a;
}


int main()
{
int a,b,c;
float d,e,f;
long g,h,i;


cin>>a>>b>>c;
cin>>d>>e>>f;
cin>>g>>h>>i;


int m;                                    //函数值为整型
m=max(a,b,c);
cout<<"max_f="<<m<<endl;


float n;                                    //函数值为实型
n=max(d,e,f);
cout<<"max_f="<<n<<endl;


long int p;                    &nbs

首页 上一页 1 2 3 4 5 6 7 下一页 尾页 2/7/7
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇Java 国际化标准程序实现 下一篇Python基础教程之网络编程

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目