0

我对 C++ 运算符重载非常陌生,并且遇到了一些初期问题。

我已经定义:

void Graph::operator>>(const char* param)

上述函数必须接受一个字符串作为输入,然后对该字符串执行某些操作。我如何调用这个函数?我可以通过哪些方式使用它?

4

4 回答 4

3

如果要定义运算符以便可以执行以下操作:

cin >> myGraph
cout << myGraph

您需要执行以下示例:

struct Entry
{
    string symbol;
    string original;
    string currency;

    Entry() {}
    ~Entry() {}
    Entry(string& symbol, string& original, string& currency)
        : symbol(symbol), original(original), currency(currency)
    {}
    Entry(const Entry& e)
        : symbol(e.symbol), original(e.original), currency(e.currency)
    {}
};


istream& operator>>(istream& is, Entry& en);
ostream& operator<<(ostream& os, const Entry& en);

然后实现运算符:

istream& operator>>(istream& is, Entry& en)
{
    is >> en.symbol;
    is >> en.original;
    is >> en.currency;
    return is;
}

ostream& operator<<(ostream& os, const Entry& en)
{
    os << en.symbol << " " << en.original << " " << en.currency;
    return os;
}

注意:在这种情况下,条目是结构,因此它的成员是公共的。如果您不想将它们公开,您可以将操作员方法定义为好友,以便他们可以访问 Entry 的私有成员。

如果成员不公开,Entry 的外观如下:

struct Entry
{
    private:
        string symbol;
        string original;
        string currency;

    public:
        Entry() {}
        ~Entry() {}
        Entry(string& symbol, string& original, string& currency)
            : symbol(symbol), original(original), currency(currency)
        {}
        Entry(const Entry& e)
            : symbol(e.symbol), original(e.original), currency(e.currency)
        {}

        friend istream& operator>>(istream& is, Entry& en);
        friend ostream& operator<<(ostream& os, const Entry& en);
};
于 2009-05-07T06:45:26.903 回答
2
Graph myGraph;
myGraph >> "bla";

请注意,您的operator>>(). 通常它是这样使用的:

NumericObject NumericObject::operator>>(NumericObject const& operand) const;
// bitshifts to the right

std::istream& operator>>(istream& in, StreamableObject& obj);
// parses a string representation of obj
于 2009-05-07T06:33:26.840 回答
1

我猜你实际上想要做的是能够编写这样的代码:

cin >> myGraph;
cout << myGraph;

请注意,图形对象实际上并不是调用其方法的对象。

在这种情况下,您真正​​想要做的是重载全局 operator>> 函数:

std::istream& operator>> (std::istream&, graph&);
std::ostream& operator<< (std::ostream&, const graph&);
于 2009-05-07T06:39:59.570 回答
0

如果您对此不熟悉,那么您选择了一个相当有趣(读作“不简单”)的问题来尝试解决。

运算符重载并不完全是函数。当编译器尝试解析如下所示的代码时,它们会被间接调用:

Graph g = new Graph();
g >> "do something";

我建议你不要这样做。由于副作用,运算符重载可能会导致非常难以解决的错误。他们对任何必须维护您的代码的人也很苛刻(可能是您忘记了为什么这样做之后)。

仅当它们的含义和使用直观时才使用运算符重载。

于 2009-05-07T06:35:51.420 回答