c++类

完整版本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;

 

原文链接: https://www.cnblogs.com/sweetlittlebaby/p/12889748.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    c++类

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/348352

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年3月2日 上午5:01
下一篇 2023年3月2日 上午5:01

相关推荐