相关疑难解决方法(0)

连接两个字符串文字

我正在阅读Koenig的Accelerated C++.他写道:"新的想法是我们可以使用+来连接字符串和字符串文字 - 或者就此而言,使用两个字符串(但不是两个字符串文字).

很好,我认为这是有道理的.现在进行两个单独的练习,意在阐明这一点.

以下定义是否有效?

const string hello = "Hello";

const string message = hello + ",world" + "!";
Run Code Online (Sandbox Code Playgroud)

现在,我尝试执行上述操作并且有效!所以我很高兴.

然后我试着做下一个练习;

const string exclam = "!";

const string message = "Hello" + ",world" + exclam;
Run Code Online (Sandbox Code Playgroud)

这没用.现在我明白它与你无法连接两个字符串文字的事实有关,但我不理解为什么我设法让第一个例子工作之间的语义差异(不是",世界"和"! "两个字符串文字?这不应该没用吗?"但不是第二个.

c++ string syntax concatenation operators

117
推荐指数
4
解决办法
13万
查看次数

错误:类型'const char [35]'和'const char [2]'到二进制'operator +'的操作数无效

在我的文件的顶部,我有

#define AGE "42"
Run Code Online (Sandbox Code Playgroud)

稍后在文件中我多次使用ID,包括一些看起来像的行

1 std::string name = "Obama";
2 std::string str = "Hello " + name + " you are " + AGE + " years old!";
3 str += "Do you feel " + AGE + " years old?";
Run Code Online (Sandbox Code Playgroud)

我收到错误:

"错误:类型'const char [35]'和'const char [2]'到二进制'运算符+''的操作数无效"

第3行.我做了一些研究,发现这是因为C++如何处理不同的字符串,并且能够通过将"AGE"更改为"string(AGE)"来修复它.但是,直到今天我才意外地错过了其中一个实例,并且想知道为什么编译器没有抱怨,即使我还有一个只是"AGE"的实例.

通过一些反复试验,我发现我只需要string(AGE)在不连接函数体中创建的另一个字符串的行上.

我的问题是"在后台发生的事情是C++不喜欢将字符串与预处理器放置的字符串连接起来,除非你还连接了你在函数中定义的字符串."

c++ string stdstring c-preprocessor

51
推荐指数
4
解决办法
10万
查看次数

通过隐式转换为字符串流式传输对象时,重载决策失败

免责声明:知道应该避免隐式转换为字符串,并且正确的方法是op<<过载Person.


请考虑以下代码:

#include <string>
#include <ostream>
#include <iostream>

struct NameType {
   operator std::string() { return "wobble"; }
};

struct Person {
   NameType name;
};

int main() {
   std::cout << std::string("bobble");
   std::cout << "wibble";

   Person p;
   std::cout << p.name;
}
Run Code Online (Sandbox Code Playgroud)

在GCC 4.3.4上产生以下结果:

prog.cpp: In function ‘int main()’:
prog.cpp:18: error: no match for ‘operator<<’ in ‘std::cout << p.Person::name’
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:112: note: candidates are: std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(std::basic_ostream<_CharT, _Traits>& (*)(std::basic_ostream<_CharT, _Traits>&)) [with _CharT = char, …
Run Code Online (Sandbox Code Playgroud)

c++ operator-overloading std implicit-conversion

19
推荐指数
2
解决办法
2135
查看次数

在 cpp 中为 double 和 string 数据类型定义运算符 +

我正在尝试使用以下函数为字符串和双定义运算符 +

string operator + (const double& b,const string a){
    return to_string(b)+a;
}
Run Code Online (Sandbox Code Playgroud)

当我进行以下操作时,效果很好

double c = 100.256;
string d = "if only";
cout<<c+d<<"\n";
Run Code Online (Sandbox Code Playgroud)

但是当我传递 const char 而不是 string 时,它会抛出编译错误('double'和'const char [4]'类型的无效操作数到二进制'operator+')

double c = 100.256;
string test = c+"sff";
Run Code Online (Sandbox Code Playgroud)

为什么不发生 const char[] "sff" 到字符串的隐式转换?

c++ operator-overloading operator-keyword explicit-conversion

3
推荐指数
1
解决办法
144
查看次数