码迷,mamicode.com
首页 > 编程语言 > 详细

一个完整的C++程序SpreadSheet - 1) 类的声明和定义

时间:2015-07-12 12:36:48      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:

1. SpreadsheetCell.h

#pragma once

#include <string>

class SpreadsheetCell
{
public:
    void setValue(double inValue);
    double getValue() const;

    void setString(const std::string& inString);
    const std::string& getString() const;

private:
    std::string doubleToString(double inValue) const;
    double stringToDouble(const std::string& inString) const;

    double mValue;
    std::string mString;
};

 

2. SpreadsheetCell.cpp

#include "SpreadsheetCell.h"

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

void SpreadsheetCell::setValue(double inValue)
{
    mValue = inValue;
    mString = doubleToString(mValue);
}

double SpreadsheetCell::getValue() const
{
    return mValue;
}

void SpreadsheetCell::setString(const string& inString)
{
    mString = inString;
    mValue = stringToDouble(mString);
}

const string& SpreadsheetCell::getString() const
{
    return mString;
}

string SpreadsheetCell::doubleToString(double inValue) const
{
    ostringstream ostr;

    ostr << inValue;
    return ostr.str();
}

double SpreadsheetCell::stringToDouble(const string& inString) const
{
    double temp;

    istringstream istr(inString);

    istr >> temp;
    if (istr.fail() || !istr.eof()) {
        return 0;
    }
    return temp;
}

 

3. SpreadSheetCellInStackTest.cpp

    (在堆栈中创建并使用对象)

#include <iostream>
#include "SpreadsheetCell.h"
#include "SpreadSheetCellInStackTest.h"

using namespace std;

void SpreadSheetCellInStackTest::run()
{
    SpreadsheetCell myCell, anotherCell;
    myCell.setValue(6);
    anotherCell.setString("3.2");

    cout << "cell 1: " << myCell.getValue() << endl;
    cout << "cell 2: " << anotherCell.getValue() << endl;
}

 

一个完整的C++程序SpreadSheet - 1) 类的声明和定义

标签:

原文地址:http://www.cnblogs.com/davidgu/p/4640721.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!