为新手提供的有关如何避免运算符重载的错误的建议 [英] Advice for novices for how to avoid bugs with operator overloading

查看:94
本文介绍了为新手提供的有关如何避免运算符重载的错误的建议的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的一个学生问了一个问题,问为什么下面的代码会产生他认为是神秘的输出.

I got a question from a student of mine asking why the following code results with what he thought to be a mysterious output.

代码:

#include <iostream>

int main() {
    char op = '+';
    int num = 9;
    std::string res =
        "a const char* concatenated with a char and std::string " 
                    + op + std::to_string(num);
    std::cout << res << std::endl;
}

好吧,他希望得到:a const char* concatenated with a char and std::string + 9,却不明白为什么他只得到std::string 9.显然,如果这是一个函数调用而不是一个运算符,则问题将立即弹出.

Well, he expected to get: a const char* concatenated with a char and std::string + 9 and couldn't understand why he gets just std::string 9. It's clear that if it was a function call and not an operator the problem would pop right away.

有何建议,我可以给新手一些有关如何避免运算符重载的错误的提示吗?

推荐答案

"a const char* concatenated with a char and std::string "const char[]文字,而不是std::string.在C样式数组中添加一个整数(char是一个小整数)会生成一个临时指针,该指针以该编号的偏移量指向该数组.

"a const char* concatenated with a char and std::string " is a const char[] literal, not a std::string. Adding an integer (char is a small integer) to a C-style array generates a temporary pointer pointing into that array at the numbered offset.

避免此类问题的一般建议:避免使用C样式的数组(包括C样式的字符串文字).

General advice to avoid this sort of problem: Avoid using C-style arrays (including C-style string literals).

您可以使用C ++字符串文字:

You can use a C++ string literal:

using namespace std::string_literals;   // need once in the code

std::string res =
    "a const char* concatenated with a char and std::string "s
                + op + std::to_string(num);

在文字末尾注意s.您将需要#include <string>-原始程序也应该具有该功能.

note the s on the end of the literal. You will need #include <string> -- the original program should have had that too.

如果您使用的旧编译器不支持std::string文字,那么也可以通过将其流式传输到内存缓冲区中来执行构建字符串的操作:

If you are using an old compiler that does not support std::string literals then building a string can also be performed by streaming into a memory buffer:

std::ostringstream buffer;
buffer << "bla bla bla" << op << num;
std::string res = buffer.str();

这篇关于为新手提供的有关如何避免运算符重载的错误的建议的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆