简体   繁体   English

我如何使用 cout << myclass

[英]How can I use cout << myclass

myclass is a C++ class written by me and when I write: myclass是我写的一个 C++ 类,当我写的时候:

myclass x;
cout << x;

How do I output 10 or 20.2 , like an integer or a float value?如何输出1020.2 ,如integerfloat值?

Typically by overloading operator<< for your class:通常通过为您的类重载operator<<

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;
}

You need to overload the << operator,您需要重载<<运算符,

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

Then when you do cout << x (where x is of type myclass in your case), it would output whatever you've told it to in the method.然后当你执行cout << x (在你的例子中xmyclass类型)时,它会输出你在方法中告诉它的任何内容。 In the case of the example above it would be the x.somevalue member.在上面的例子中,它是x.somevalue成员。

If the type of the member can't be added directly to an ostream , then you would need to overload the << operator for that type also, using the same method as above.如果成员的类型不能直接添加到ostream ,那么您还需要使用与上面相同的方法重载该类型的<<运算符。

it's very easy, just implement :这很容易,只需实现:

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

You need to return a reference to os in order to chain the outpout (cout << foo << 42 << endl)您需要返回对 os 的引用以链接输出(cout << foo << 42 << endl)

Even though other answer provide correct code, it is also recommended to use a hidden friend function to implement the operator<< .即使其他答案提供了正确的代码,也建议使用隐藏的朋友函数来实现operator<< Hidden friend functions has a more limited scope, therefore results in a faster compilation.隐藏友元函数的范围更有限,因此编译速度更快。 Since there is less overloads cluttering the namespace scope, the compiler has less lookup to do.由于混乱命名空间范围的重载较少,编译器的查找工作也较少。

struct myclass { 
    int i;

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

int main() { 
    auto const x = myclass{10};
    std::cout << x;

    return 0;
}

Alternative:选择:

struct myclass { 
    int i;
    inline operator int() const 
    {
        return i; 
    }
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM