如何使用 cout <<我的课

2022-01-14 00:00:00 class input integer c++

myclass是我写的一个C++类,我写的时候:

myclass is a C++ class written by me and when I write:

myclass x;
cout << x;

如何输出 1020.2,如 integerfloat 值?

How do I output 10 or 20.2, like an integer or a float value?

推荐答案

通常通过为您的类重载 operator<<:

Typically by overloading operator<< for your class:

struct myclass { 
    int i;
};

std::ostream &operator<<(std::ostream &os, myclass const &m) { 
    return os << m.i;
}

int main() { 
    myclass x(10);

    std::cout << x;
    return 0;
}

相关文章