1

У меня есть класс, и дружественная функция outer(...).

   template <unsigned int columns>
class Perceptron {
public:
    Perceptron(double norma, int flag, std::vector<std::tuple<int, bool>> function);
private:
auto net(int step) ->double;
auto f(double netParam)->bool;
auto learning(std::vector<std::tuple<int, bool>> & function, bool printOut)->bool;
auto step(int step)->void;
auto logisticFunction(double netParam)->double;

friend auto outer(const int& errors, const int& epochCount, const Perceptron<columns>* obj)->void;

int flag;
double norma;
std::vector<std::tuple<int, bool>> function;
std::vector<double> weights;


template <unsigned int columns>
auto Perceptron<columns>::learning(std::vector<std::tuple<int, bool>> & function, bool printOut)->bool {
    int epochCount = 0, errors = 1;

    while (errors != 0) {
        if (epochCount > 40) return false;

        errors = 0;
        for (int i = 0; i < pow(2, columns - 1); i++) {
            std::bitset<columns> bits(i + pow(2, columns - 1));
            if (std::get<1>(this->function[i]) != f(net(i)))
                errors++;
        }

        if (printOut)
            outer(errors, epochCount, this);


        for (int i = 0; i < this->function.size(); i++)
            this->step(i);

        epochCount++;
    }
    return true;
}

template <unsigned int columns>
auto outer(const int& errors, const int& epochCount, const Perceptron<columns>* obj)->void {
    std::cout << "Epocha " << epochCount << ":\nY = (";
    for (size_t i = 0; i < obj->function.size(); i++)
        std::cout << obj->f(obj->net(std::get<0>(obj->function[i]))) << ((i == (pow(2, columns - 1) - 1)) ? "),\n" : ",");
    std::cout << "W = (";
    for (int i = 0; i < columns; i++)
        std::cout << obj->weights[i] << ((i == columns - 1) ? "), " : ",");
    std::cout << "E = " << errors << "\n";
}

Ошибка:

Ошибка LNK2019 ссылка на неразрешенный внешний символ "void __cdecl outer(int,int,class Perceptron<5> *)" (?outer@@YAXHHPAV?$Perceptron@$04@@@Z) в функции "private: bool __thiscall Perceptron<5>::learning(class std::vector,class std::allocator > &,bool)" (?learning@?$Perceptron@$04@@AAE_NAAV?$vector@V?$tuple@H_N@std@@V?$allocator@V?$tuple@H_N@std@@@2@@std@@_N@Z) ITIB1 c:\Users\kudas\source\repos\ITIB1\ITIB1\ITIB1.obj 1

1
  • 1
    Во-первых, какую ошибку и где? Во-вторых, this - указатель, а функция принимает ссылку. out(*this) 10 апр 2018 в 7:20

1 ответ 1

2

Вообще-то, вот так:

template<unsigned int col>
class A{
public:
    A(){ out(*this); };
    friend auto out(const A<col>& in){...};
};

Хотя формально до окончания конструктора объект this не является окончательно созданным :)

Но если у вас out шаблонный - то и объявлять его надо как шаблонный в самом классе:

#include <iostream>
#include <iomanip>

using namespace std;

template<unsigned int col>
class A{
public:
    A(){ out(*this); };

    template<unsigned int c>
    friend void out(const A<c>&);
};

template<unsigned int c>
void out(const A<c>&)
{}


int main(int argc, const char * argv[])
{
    A<5> a;
    out(a);
}
6
  • да, это я для примера написал, на деле у меня из метода класса вызывается дружественная, но почему то теперь выдает : "ссылка на неразрешенный внешний символ"
    – Kayrosik
    10 апр 2018 в 7:38
  • Покажите весь код (ru.stackoverflow.com/help/mcve)
    – Harry
    10 апр 2018 в 7:43
  • добавил код в вопрос
    – Kayrosik
    10 апр 2018 в 7:49
  • @Harry А теперь без смайликов поясните, с каких это пор объект внутри конструктора может быть не до конца создан? Не до конца инициализирован - да.
    – gbg
    10 апр 2018 в 7:52
  • @gdb Объект - объект, а не выделенная память! - создан, когда он находится в корректном состоянии. Ваше "создан, но не до конца инициализирован" - примерно как автомобиль, который создан, но движок в него не поставлен, а вызов какой-то функции с передачей ему такого объекта - все равно что попытка покататься на таком автомобиле...
    – Harry
    10 апр 2018 в 8:07

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими условиями использования и подтверждаете, что прочитали и поняли наши политику конфиденциальности и нормы поведения.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.