C++:概述

时间:2023-03-09 01:33:01
C++:概述

1.基本的输入输出,使用cin>>输入输入、使用cout<<输出

#include<iostream>
using namespace std;
int main()
{
int a,b,d,min;
cout<<"Enter two numbers:"<<endl;
cin>>a>>b;
cout<<"min = "<<(min=a>b? b:a);
for(d=;d<min;d++)
if(((a%d)==) && ((b%d)==)) break;
if (d==min)
{
cout<<"no common denominators"<<endl;
return ;
}
cout<<"the lowest common denominator is"<<d<<endl;
return ;
Enter two numbers:

min =
the lowest common denominator is2
Program ended with exit code:

2.使用引用,引用用地址符号&表示,引用就是给变量或者常量起的另一个别名,操作的还是同一个数据

//引用当做返回值

/*
需求:使用引用返回函数值
*/
#include<iostream>
using namespace std;
int &f(int &i) //定义函数返回一个整数类型的引用,等价于返回数值i
{
i+=;
return i;
}
int main()
{
int k=;
int &m=f(k); //k=i=10
cout<<k<<endl;
m=;
cout<<k<<endl;
return ;

Program ended with exit code: 

//引用当做参数

/*
需求:引用作为函数参数
*/
#include<iostream>
using namespace std;
void f(int &m,int n)
{
int temp;
temp = m;
m = n;
n =temp;
}
int main()
{
int a = ,b = ;
cout<<"a = "<<a<<" "<<"b = "<<b<<endl;
f(a,b);
cout<<"a = "<<a<<" "<<"b = "<<b<<endl;
return ;
a =  b =
a = b =
Program ended with exit code:

3.使用作用域运算符::,作用变量或常量或函数的有效区域

/*
需求:作用域运算符::
*/
#include<iostream>
using namespace std;
int i=;
int main ()
{
int i;
i = ;
::i = i+;
cout<<i<<endl;
cout<<::i<<endl;
return ;
}

Program ended with exit code: 

4.结构体的简单使用,它有自己的属性成员和方法成员,需要创建结构体成员变量才能调用自己的属性和方法

//#include<iostream>
//#include<cmath>
//using namespace std;
#include<iostream.h>
#include<math.h>
struct Complex //声明一个名为Complex的结构体
{
double real; //数据成员,复数的实部
double imag; //数据成员,复数的虚部
void init(double r,double i) //成员函数init,给real和imag赋给初值
{
real = r;
imag = i;
}
double abscomplex() //成员函数,求复数的绝对值
{
double t;
t = real*real+imag*imag;
return sqrt(t);
}
};
int main()
{
Complex A; //定义结构体Complex的成员变量A
A.init(1.1,2.2); //调用成员函数init,给real和imag赋给初值
cout<<"复数的绝对值是:"<<A.abscomplex()<<endl; //调用成员函数abscomplex
return ;
}
复数的绝对值是:2.45967
Program ended with exit code: