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

本文介绍了一个简单的表格单元格类的设计与实现,该类能够处理字符串与数值之间的转换,并通过一个测试程序验证了其功能。代码示例展示了如何在堆栈中创建并使用此类的对象。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值