我正在编写自己的类(称为“Longer”),这样它可以容纳一个没有任何上限的数字,这与 int 不同。我为此使用 std::string 。 我在执行加法时遇到问题。
- 如果我简单地添加两个字符串,我无法得到正确的结果。
- 我想到将字符串转换为整数,然后执行加法, 但长字符串无法转换为 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/