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

简介: 1. SpreadsheetCell.h #pragma once #include class SpreadsheetCell { public: void setValue(double inValue); double getValue() cons...

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;
}

 

目录
相关文章
|
2天前
|
安全 编译器 程序员
【C++篇】C++类与对象深度解析(六):全面剖析拷贝省略、RVO、NRVO优化策略
【C++篇】C++类与对象深度解析(六):全面剖析拷贝省略、RVO、NRVO优化策略
13 2
|
2天前
|
存储 C++
【C++篇】C++类和对象实践篇——从零带你实现日期类的超详细指南
【C++篇】C++类和对象实践篇——从零带你实现日期类的超详细指南
12 2
【C++篇】C++类和对象实践篇——从零带你实现日期类的超详细指南
|
2天前
|
存储 编译器 C语言
C++类与对象深度解析(一):从抽象到实践的全面入门指南
C++类与对象深度解析(一):从抽象到实践的全面入门指南
19 8
|
2天前
|
C++
【C++】实现日期类相关接口(三)
【C++】实现日期类相关接口
|
2天前
|
安全 C语言 C++
【C++篇】探寻C++ STL之美:从string类的基础到高级操作的全面解析
【C++篇】探寻C++ STL之美:从string类的基础到高级操作的全面解析
22 4
|
2天前
|
存储 编译器 数据安全/隐私保护
【C++篇】C++类与对象深度解析(四):初始化列表、类型转换与static成员详解2
【C++篇】C++类与对象深度解析(四):初始化列表、类型转换与static成员详解
13 3
|
2天前
|
编译器 C++
【C++篇】C++类与对象深度解析(四):初始化列表、类型转换与static成员详解1
【C++篇】C++类与对象深度解析(四):初始化列表、类型转换与static成员详解
18 3
|
2天前
|
安全 编译器 C++
【C++篇】C++类与对象深度解析(三):类的默认成员函数详解
【C++篇】C++类与对象深度解析(三):类的默认成员函数详解
9 3
|
2天前
|
存储 编译器 程序员
【C++篇】手撕 C++ string 类:从零实现到深入剖析的模拟之路
【C++篇】手撕 C++ string 类:从零实现到深入剖析的模拟之路
22 2
|
2天前
|
存储 设计模式 编译器
【C++篇】C++类与对象深度解析(五):友元机制、内部类与匿名对象的高级应用
【C++篇】C++类与对象深度解析(五):友元机制、内部类与匿名对象的高级应用
12 2