开发者

Defining operator<< Inside Class

开发者 https://www.devze.com 2023-02-14 07:10 出处:网络
Consider the following code: class MyClass { template <typename Datatype> friend MyClass& operator<<(MyClass& MyClassReference, Datatype SomeData);

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 op开发者_运维知识库erator<< 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);

.


I'm not sure this is good idea, but yes -- when you define operator<< as a member function, *this will essentially equivalent to the first parameter you've defined in your operator.


You were almost there:

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

精彩评论

暂无评论...
验证码 换一张
取 消