`
guoyiqi
  • 浏览: 968079 次
社区版块
存档分类
最新评论

c++ 学习资料

阅读更多

swap

 

#include <iostream>
#include <vector>
using namespace std;

int swap1(int* px,int* py){
int z=*px;
*px=*py;
*py=z;
return 0;
}

int swap2(int &ix,int &iy){
int z=ix;
ix=iy;
iy=z;
return 0;
}


int main(int argc, char* argv[])
{
int x,y;
cout<<"intput x and y:"<<endl;

cin>>x;
cin>>y;
swap1(&x,&y);
cout<<"swap1:"<<x<<","<<y<<endl;
swap2(x,y);
cout<<"swap2:"<<x<<","<<y<<endl;
 
}

 

 

 

 

 

-------------------------------------------------------

seq

 

#include <iostream>
#include <vector>
using namespace std;

bool fibon_elem(int iPos, int &iElem)
{
    int n2 = 1, n1 = 1;
    if (iPos <= 0 || iPos >= 1024)
    {
        iElem = 0; return false;
    }
    iElem = 1;
    for (int iX = 3; iX <= iPos; iX++)
    {
        iElem = n2 + n1;
        n2 = n1;
        n1 = iElem;
    }
    return true;
}


int fibon_elem(int iPos)
{
    int n2 = 1, n1 = 1;
    int iElem = 1;
   
    for (int iX = 3; iX <= iPos; iX++)
    {
        iElem = n2 + n1;
        n2 = n1;
        n1 = iElem;
    }
    return iElem;
}


vector<int> fibon_seq(int iLength)
{
  if (iLength <= 0 || iLength >= 1024)
    {
        cerr <<"Length"<<iLength<<"not supported, reset to 8"<<endl;
        iLength = 8;
    }
    vector<int> Elems( iLength );
    for (int iX = 0; iX < iLength; iX++){
        if (iX == 0 || iX == 1)
        {
            Elems[iX] = 1;
        }
        else
        {
            Elems[iX] = Elems[iX-1] + Elems[iX-2];
        }
    }
    return Elems;
}


int main(int argc, char* argv[])
{
 int x,y;
 cout<<"please input a num(from 0-1024):";
 cin>>x;
 cout<<"first result:"<<fibon_elem(x);
 if(fibon_elem(x,y))
  cout<<endl<<"second result:"<<y;
 else
  cout<<endl<<"second result:error";
 vector<int> Elems=fibon_seq(x);
 cout<<endl<<"third result:";
 for(int i=0;i<Elems.size();i++)
  cout<<Elems[i]<<",";
 cout<<endl;
 return 0;
}

 

--------------------------------------------

根据main的参数选择函数

int main(int argc, char* argv[])
{
 if(argc!=2){
  cout<<"input error,like guo1.exe c/e"<<endl;
  return 0;
 }

 if(strcmp(argv[1],"c")==0)
  cout<<"c";
 else
  cout<<"e";
 
}

 

-----------------------

#include <iostream>
#include <vector>
using namespace std;


class X
{
public:
   int mf1(){cout<<"hello";return 0;};
      int mf2() {  return mf3();  }
private:
      int mf3(){cout<<"hello";return 0;};
    
} x;

void main()
{
     x.mf1();  //yes
     x.mf2();
  //x.mf3();  //Error! Private member can’t be accessed out of the class
}

 

---------------y

#include <iostream>
#include <vector>
using namespace std;


class Y
{
public:
      int _m1;
      int get_m2() { return _m2;}
      void set_m2(int x) { _m2 = x;}
private:
      int _m2;   
} y;

void main()
{
     y._m1++;  //Not suggested! Direct access data members
  cout<<y._m1;
     y.set_m2(1);  //Suggested! The data member is accessed under control
  cout<<y.get_m2();
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics