what is wrong with this program?

后端 未结 4 1373
时光说笑
时光说笑 2021-01-27 04:54
#include 
#include 
#include 

using namespace std;

int main() {
    string x;
    getline(cin,x);
    ofstream o(\"f:/demo         


        
4条回答
  •  无人共我
    2021-01-27 05:22

    You seem to have an incorrect model of sizeof, so let me try to get it right.

    For any given object x of type T, the expression sizeof(x) is a compile-time constant. C++ will never actually inspect the object x at runtime. The compiler knows that x is of type T, so you can imagine it silently transforming sizeof(x) to sizeof(T), if you will.

    #include 
    
    int main()
    {
        std::string a = "hello";
        std::string b = "Stack Overflow is for professional and enthusiast programmers, people who write code because they love it.";
        std::cout << sizeof(a) << std::endl;   // this prints 4 on my system
        std::cout << sizeof(b) << std::endl;   // this also prints 4 on my system
    }
    

    All C++ objects of the same type take up the exact amount of memory. Of course, since strings have vastly different lengths, they will internally store a pointer to a heap-allocated block of memory. But this does not concern sizeof. It couldn't, because as I said, sizeof operates at compile-time.

提交回复
热议问题