gpt4 book ai didi

c++ - 在 C++ 中重载 + 运算符时第一个参数是字符串的问题

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:08:48 27 4
gpt4 key购买 nike

我有一个自制的字符串类:

//String.h
String & operator = (const String &);
String & operator = (char*);
const String operator+ (String& s);
const String operator+ (char* sA);
.
.

//in main:
String s1("hi");
String s2("hello");

str2 = str1 + "ok";//this is ok to do
str2 = "ok" + str1;//but not this way

//Shouldn't it automatically detect that one argument is a string and in both cases?

最佳答案

+ 运算符不应是成员函数,而应是自由函数,以便可以对其任一操作数执行转换。最简单的方法是将 operator += 编写为成员,然后使用它来实现 operator + 的自由功能。像这样的东西:

String operator +( const String & s1, const String & s2 ) {
String result( s1 );
return result += s2;
}

正如其他人所建议的,出于可能的效率原因,您可以为 const char * 重载,但上面的单个函数是您实际需要的。

请注意,您的代码目前应该给出以下错误:

String s1("hi");
String s2("hello");
str2 = str1 + "ok"; // not OK!!!

类似于:

warning: deprecated conversion from string constant to 'char*'

因为字符串文字(常量)“ok”是 const char *,而不是 char *。如果您的编译器没有给出此警告,您应该认真考虑升级它。

关于c++ - 在 C++ 中重载 + 运算符时第一个参数是字符串的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2788352/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com