我正在尝试从初学者的书中理解以下代码。(编辑:"使用 C++ 的编程原理和实践"第 1085 页)我不太明白为什么根据评论制作临时字符串。
const char* string_tbl[ ] = { "Mozart", "Grieg", "Haydn", "Chopin" };
const char* f(int i) { return string_tbl[i]; }
void g(string s){}
void h()
{
const string& r = f(0); // bind temporary string to r
g(f(1)); // make a temporary string and pass it
string s = f(2); // initialize s from temporary string
cout << "f(3): " << f(3) // make a temporary string and pass it
<<" s: " << s
<< " r: " << r << 'n';
}
f()
返回一个指向常量字符的指针,对吧?
const string& r = f(0);
不应该为引用变量分配一个"指向字符的指针"(在本例中为全局数组中的字符串文字)以便可以使用 r[] 等访问原始变量(只读)吗?
g(f(1));
传递一个指针指向g()
然后用指针初始化string s
的位置?
我错过了什么?const char* 在从函数返回时是否总是生成临时字符串?
有一个隐式转换,代码
string s = f(2);
等于
string s = string(f(2));
我不太明白为什么根据评论制作临时字符串。
整个问题是char const*
和std::string
是完全不同的数据类型。
为了比较:
class A { };
class B { };
void f(A a);
void g()
{
B b;
f(b); // does not work...
}
我很确定你已经遇到过了。
现在让我们更改类 A:
class A
{
public:
A() { } // default constructor
A(B b) { } // accepting an instance of B
};
现在,您可以执行以下操作:
B b;
f(A(b)); // create a TEMPORARY A from B; you need it, as f ONLY accepts an A!
f(b); // again, create a temporary just as before - this time IMPLICITLY
您可以通过显式构造函数来禁止从 B 隐式创建 A:
class A
{
public:
A() { }
explicit A(B b) { } // now A cannot be created implicitly any more
};
B b;
//f(b); // now is not accepted by compiler any more
f(A(b)); // this still works, of course
与std::string
完全相同:它有一个接受char const*
的非显式构造函数...