我有下面的代碼,其與無警告(-Wall -pedantic)與克++C++傳遞字符串而不是const std :: string&?
#include <iostream>
#include <string>
using namespace std;
class Foo
{
public:
Foo(const std::string& s) : str(s)
{ }
void print()
{
cout << str << endl;
}
private:
const std::string& str;
};
class Bar
{
public:
void stuff()
{
Foo o("werd");
o.print();
}
};
int main(int argc, char **argv)
{
Bar b;
b.stuff();
return 0;
}
但是當我運行它,只有換行打印出編譯。 發生了什麼事?
如果我做這裏面的東西:
string temp("snoop");
Foo f(temp);
f.print();
然後正常工作!
歡呼聲,不知道爲什麼我的大腦沒有得到:s – 2010-12-07 01:50:49