我试图通过试验构造函数和引用来学习。我按如下方式编写了这个类,我希望在课后写出答案
#include <iostream>
#include <string>
class human {
public:
const std::string& m_name;
void printit() {
std::cout <<"printit "<< m_name << std::endl;
}
human(const std::string& x):m_name(x){
std::cout << "the constructor "<< m_name << std::endl;
}
~human() {
std::cout << "dest called"<< std::endl;
}
};
int main()
{
human x("BOB")
x.printit();
return (0);
}
> the constructor BOB
> printit BOB
> dest called
然而我得到这样的东西。调用该函数时m_name
丢失了。使用int
代替string
时,同一个班级正常。有什么问题?
> the constructor BOB
> printit
> dest called
现在是与int const
引用相同的类
#include <iostream>
class human {
public:
const int& m_name;
void printit() {
std::cout <<"printit "<< m_name << std::endl;
}
human(const int& x):m_name(x){
std::cout << "the constructor "<< m_name << std::endl;
}
~human() {
std::cout << "dest called"<< std::endl;
}
};
int main()
{
human x(3);
x.printit();
return (0);
}
在这种情况下,我得到了正确答案。
> the constructor 3
> printit 3
> dest called
有人可以解释原因吗?内置类型是否仍然存在?