c++ - 添加用户定义类型 C++

标签 c++ string class addition

我正在编写自己的类(称为“Longer”),这样它可以容纳一个没有任何上限的数字,这与 int 不同。我为此使用 std::string 。 我在执行加法时遇到问题。

  1. 如果我简单地添加两个字符串,我无法得到正确的结果。
  2. 我想到将字符串转换为整数,然后执行加法, 但长字符串无法转换为 int。

如何定义我自己的添加两个字符串的方式,以便获得所需的结果?这是代码:

加长.h

#pragma once
#include <string>

class Longer
{
public:
   Longer(std::string number);
   Longer add(Longer num2);
   void print();
private:
   std::string number;
};

加长.cpp

#include "Longer.h"
#include <iostream>
#include <string>

Longer::Longer(std::string num): number(num)
{
}

Longer Longer::add(Longer num2){
  return Longer(number+num2.number);
}

void Longer::print(){
std::cout<<number<<"\n";
}

主要.cpp

#include <iostream>
#include "Longer.h"

int main(){

Longer num1("123456789101112");
Longer num2("121110987654321");


Longer num3 = num1.add(num2);
num3.print();

}

最佳答案

我不奇怪加法不能像您预期的那样工作。 std::string 并不意味着用作任意长度的数字容器,这就是原因。

您必须定义自己的方式来“添加”两个字符串,这应该包括向后迭代两个字符串(从末尾开始)并通过将它们解释为数字来比较单个字符。

关于c++ - 添加用户定义类型 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25227394/

相关文章:

android - Android ListView 项目中的长字符串

c++ - 如何计算 char 数组中元素的数量?

Python 字符串相似度(具有复杂性)

c++ - 从展平的 3D 数组计算 3D 坐标

c++ - 限制int数据类型的大小

Python 类继承 - 如何使用它连接到 mysql 数据库

jquery - 查找多个类中包含类名

javascript - 使用 Typescript 或 javascript 动态获取类成员名称和值

c++ - float 的散列函数

c++ - 如何为我的程序创建静态库?