簡體   English   中英

在非靜態成員 function 之外無效使用“this”?

[英]invalid use of 'this' outside of a non-static member function?

我在我的Matrix<T> class 的公共部分中編寫了以下代碼:

#include <iostream>
#include "Auxiliaries.h"

namespace mtm {
    template<class T>
    class Matrix {
    private:
        Dimensions dimensions;
        T *data;

    public:

        iterator_impl<T> begin(){};

        class AccessIllegalElement;

        class IllegalInitialization;

        class DimensionMismatch;

        Matrix(const Dimensions &matrix_dimensions, const T &initial_value = T());

    };


/**Iterators**/

    template<typename T>
    class iterator_impl;

    template<typename T>
    iterator_impl<T> begin(){
        return iterator(this, 0);
    }

    template<typename T>
    class iterator_impl{
    private:
        const Matrix<T> *matrix;
        int index;
        friend class Matrix<T>;

    public:
        iterator_impl(const iterator_impl &) = default;

        iterator_impl &operator=(const iterator_impl &) = default;

        ~iterator_impl() = default;

        iterator_impl(const Matrix<T> *matrix, int index)
                : matrix(matrix), index(index) {}

        iterator_impl &operator++()
        {
            ++index;
            return *this;
        }

        iterator_impl operator++(int)
        {
            iterator_impl result = *this;
            ++*this;
            return result;
        }

        bool operator==(const iterator_impl &it) const
        {
            return index == it.index;
        }

        bool operator!=(const iterator_impl &it) const
        {
            return !(*this == it);
        }

        T &operator*() const {
            return matrix->data[index];
        }

    };
    template<typename T>
    using iterator = iterator_impl<T>;
    template<typename T>
    using const_iterator = iterator_impl<const T>;

}

但我收到以下錯誤:

invalid use of 'this' outside of a non-static member function
        return iterator(this, 0);

我在這里做錯了什么,我該如何解決這個問題?

我的 class:

template<class T>
class Matrix {
private:
    Dimensions dimensions;
    T *data;

public:

    iterator_impl<T> begin(){};
    //....
}

https://wandbox.org/permlink/R4rQjGVNZWUHtMqj

在這種情況下, this意味着什么?

template<typename T>
iterator_impl<T> begin(){
    return iterator(this, 0);
}

It should be a pointer to the object of the class the method belongs to, but the begin function is a free function that is not a member of any class.

你打算如何使用這個 function? 基本模式是:

container.begin();

或者

begin(container);

在這兩種情況下,都有一個container :您在樣品中忘記了 class 的 object。

更新

根據您的更新, this應該是指向Matrix object 的指針。 您已經聲明了該方法,而不是讓我們定義它。 實施實際上取決於您,我不確定它是否正確。 關鍵部分是您忘記在 function 簽名中指定 class :

template<typename T>
iterator_impl<T> Matrix<T>::begin() {
    return iterator(this, 0);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM