我试图通过尝试构造函数和引用来学习。我写的课如下,我期待课后写的答案
#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
有人可以解释原因吗?内置类型是否持续存在?