コンストラクターと参照を試して学習しようとしています。私は次のようにクラスを書きました。クラスの後に書かれた答えを期待しています
#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
誰かが理由を説明できますか?組み込み型は保持されますか?