簡體   English   中英

為什么在c ++中會顯示“找不到構造函數”?

[英]Why does it say “can't find constructor” in c++?

#include <iostream>

using namespace std;

template <class T>
class ring {
private:
    T *m_values;
    int m_size;
    int m_index;

public:
    class iterator;

public:
    ring(int size):
            m_size(size), m_index(0), m_values(NULL) {
        m_values = new T[size];
    }

    ~ring() {
        delete [] m_values;
     }

    int size() const {
        return m_size;
    }

    iterator begin() {
        return iterator(0, *this);
    }

    iterator end() {
        return iterator(m_size, *this);
    }

    void add(T value) {
        m_values[m_index] = value;
        m_index = (m_index + 1) % m_size;
    }

    T &get(int pos) {
        return m_values[pos];
    }
};

template<class T>
class ring<T>::iterator {
private:
     int m_pos;
     ring &m_ring;
public:
    iterator(int m_pos, ring &m_ring): m_pos(m_pos), m_ring(m_ring) {};

    iterator &operator++(int) {
        m_pos++;
        return *this;
    }

    iterator &operator++() {
        m_pos++;
        return *this;
    }

    bool operator!=(const iterator &other) {
        return other.m_pos != m_pos;
    }

    T &operator*() {
        return m_ring.get(m_pos);
    }
};

這是c ++代碼。 我是C ++的新手,CLion的這段代碼在begin()和end()函數中給我“類迭代器沒有構造函數iterator(int,ring)”。 有人能給我一些暗示,為什么即使我定義了它也會發生這種情況?

順便說一句:這是來自udemy的“學習高級C ++編程”講座44。

更新:一些評論發現我沒有定義,僅聲明。 這不是原因,因為我在單獨的.cpp文件中定義了它。 我也嘗試內聯定義它,但仍然給我來自CLion的相同錯誤消息。

您在這里聲明構造函數

iterator(int m_pos, ring &m_ring);

但沒有定義此特殊成員函數。 如果您提供一個,那可能很好

iterator(int m_pos, ring &m_ring) : m_pos(m_pos), m_ring(m_ring)
{
    /* Maybe some other stuff... */
}

聲明了interator(int,ring),但未定義它。 那就是問題所在。

聲明與定義

聲明提供符號的基本屬性:符號的類型和名稱。 定義提供了該符號的所有詳細信息-如果它是一個函數,它將做什么? 如果是一個類,它具有哪些字段和方法; 如果是變量,則存儲該變量。 通常,編譯器只需要聲明某些內容即可將文件編譯為目標文件,並期望鏈接程序可以從另一個文件中找到該定義。 如果沒有源文件定義符號,但已聲明它,則在鏈接時抱怨未定義符號會出錯。

src: https//www.cprogramming.com/declare_vs_define.html

暫無
暫無

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

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