小编Pau*_*aul的帖子

'int' 和自定义类之间的添加

当我发现一些东西时,我正在尝试在 python 中使用 dunders:假设我创建了一个类:

class MyInt:
    def __init__(self, val):
        self.val = val

    def __add__(self, other):
        return self.val + other

a = MyInt(3)
Run Code Online (Sandbox Code Playgroud)

__add__工程时,这是运行完美的罚款:

>>> print(a + 4)
7
Run Code Online (Sandbox Code Playgroud)

但是,当我运行此命令时:

>>> print(4 + a)
TypeError: unsupported operand type(s) for +: 'int' and 'MyInt'
Run Code Online (Sandbox Code Playgroud)

我知道该int课程不支持添加 with MyInt,但是有什么解决方法吗?

python python-3.x

7
推荐指数
1
解决办法
94
查看次数

字符串添加期间的未知字符

最近开始自学C++,上网找了些挑战。我发现了一个挑战,需要我将字符串的每个字符都加倍。(例如:“abcd”->“aabbccdd”)

我做了一个简单的程序:

#include <iostream>
using namespace std;

string doubleChar(string str) {
    string result = "";
    for (int i=0; i<str.length(); i++){
        result += str[i] + str[i];
    }
    return result;
}

int main()
{
    string stuff = "Example Text";
    cout << doubleChar(stuff);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我期望"EExxaammppllee TTeexxtt",或者至少是如果代码错误我可以推断出错误的结果。但是,当我运行下面的代码时,得到了一个相当奇怪的结果:"è??????@¿???"

我对 C++ 真的很陌生,对它一无所知,所以我不知道在线谷歌什么。我尝试搜索“在 C++ 中添加字符串时的奇怪字符”或类似的东西,但找不到任何东西。我怀疑它可能与str[i] + str[i]

提前致谢

c++

0
推荐指数
1
解决办法
71
查看次数

标签 统计

c++ ×1

python ×1

python-3.x ×1