完整版本c++类:
/** * A class for simulating an integer memory cell. */ class IntCell { public: /** * construct the IntCell. * Initial value is 0. */ IntCell() {storeValue=0;} /** * Initial value is initiValue. */ IntCell(int initialVaule) { storeValue=initialVaule;} /** * return storeValue. */ int read() { return storeValue; } /** * change tne stored value to x. */ void write(int x) { storeValue =x ; } private: int storeValue; };
改进版:
#include<bits/stdc++.h> using namespace std; class IntCell { public: explicit IntCell(int initialValue=0) : storeValue {initialValue} { } int read() const{ return storeValue; } void write(int x) { storeValue =x ; } private: int storeValue; }; int main(void) { IntCell m; m.write(5); cout<<"Cell contents:"<<m.read()<<endl; system("pause"); return 0; }
explicit为了防止被强制转化,
三种声明类的方式:
IntCell obj1; // Zero parameter constructor, same as before(0参数)
IntCell obj2{ 12 }; // One parameter constructor, same as before(1参数)
IntCell obj4{ }; // Zero parameter constructor(0参数)
c++vector使用:
打表:
#include<bits/stdc++.h> using namespace std; int main(void) { vector<int> squares(100); for(int i=0; i<squares.size(); i++) squares[i]=i*i; for(int i=0; i<squares.size(); i++) cout<<i<<" "<<squares[i]<<endl; system("pause"); return 0; }
c++11;
vector <int> daysInMonth(12);
size为12的向量,
旧版的遍历向量元素的方式:
int sum = 0;
for( int i = 0; i < squares.size( ); ++i )
sum += squares[ i ];
c++11:
int sum = 0;
for( int x : squares )//vector是int型的
sum += x;
c++11还保留自动推断类型auto;
int sum = 0;
for( auto x : squares )
sum += x;