简体   繁体   中英

Defining operator<< Inside Class

Consider the following code:

class MyClass
{
    template <typename Datatype>
    friend MyClass& operator<<(MyClass& MyClassReference, Datatype SomeData);
    // ...
};

template <typename Datatype>
MyClass& operator<<(MyClass& MyClassReference, Datatype SomeData)
{
    // ...
}

How can I define operator<< inside the class, rather than as a friend function? Something like this:

class MyClass
{
    // ...

    public:

    template <typename Datatype>
    MyCLass& operator<<(MyClass& MyClassReference, Datatype SomeData)
    {
        // ...
    }
};

The above code produces compilation errors because it accepts two arguments. Removing the MyClassReference argument fixes the errors, but I have code that relies on that argument. Is MyClassReference just the equivalent of *this ?

You have

template <typename Datatype> MyClass& operator<<(MyClass& MyClassReference, Datatype SomeData);

inside of the class. It is a method of the class MyClass . Non-static methods have an implicit parameter called the this pointer. The this pointer is a pointer to the object the method was called on. You do not need the MyClassReference parameter because the this pointer fulfills that purpose.

Change that method declaration to

template <typename Datatype> MyClass& operator<<(Datatype SomeData);

.

我不确定这是个好主意,但是 - 当你将operator<<定义为成员函数时, *this基本上等同于你在运算符中定义的第一个参数。

You were almost there:

class MyClass
{
    template <typename Datatype>
    friend MyClass& operator<<(MyClass& MyClassReference, Datatype SomeData) 
    {
        // ...
    }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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