如何在C ++中重载流操作符

时间:2011-10-28 01:43:10

标签: c++

我需要类来重载流操作符<< (插入者)和>> (提取器) 插入或提取私有整数变量

3 个答案:

答案 0 :(得分:1)

一个选项如下:

#include <iostream>

class C
{
private:
    int i;

    friend std::ostream& operator<<(std::ostream& os, const C& rhs)
    {
        os << rhs.i;
        return os;
    }

    friend std::istream& operator>>(std::istream& is, C& rhs)
    {
        is >> rhs.i;
        return is;
    }
};

int main()
{
    C c;
    std::cin >> c;
    std::cout << c << '\n';
    return 0;
}

答案 1 :(得分:0)

到你自己的班级?请看一下这个链接:http://www.cs.caltech.edu/courses/cs11/material/cpp/donnie/cpp-ops.html

简而言之,您可以在课堂上添加以下内容:

ClassName & operator<<(int rhs) {
    mylocalint = rhs;
}
ClassName & operator>> (int *rhs) {
    *rhs = mylocalint;
}

答案 2 :(得分:0)

class myclass {
private: int variable;
friend std::ostream& operator<<(std::ostream& out, const myclass& inst);
friend std::istream& operator>>(std::istream& out, myclass& inst);
};

std::ostream& operator<<(std::ostream& out, const myclass& inst)
{
    return out << inst.variable;
}

std::istream& operator>>(std::istream& in, myclass& inst)
{
    return in >> inst.variable;
}

int main() {
    myclass obj;
    std::cin >> obj;
    std::cout << obj;
}