Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > C/C++: Общие вопросы > Проблема с перегрузкой опер. у класса от vector<>


Автор: Elfet 18.1.2010, 22:57
Приветствую! 

Пожалуйста, помогите разобраться почему следующий код не работает:
Physical.h:
Код

#ifndef PHYSICAL_H
#define PHYSICAL_H
#include "../main.h"

// Физические переменные

class Physical : public vector<double>
{
public:
    Physical()
        : vector<double>()
    { }
    Physical(size_t size)
        : vector<double>(size)
    { }

    string ToString()
    {
        std::stringstream oss;
        oss << "Physical( ";
        for(unsigned i = 0; size(); i++)
        {
            oss << i << ": " << at(i) << " ;";
        }
        oss << " )";
        return oss.str();
    }

    friend Physical operator+(Physical ob1, Physical ob2);
    friend Physical operator-(Physical ob1, Physical ob2);
    friend Physical operator*(Physical ob1, double scale);
    friend Physical operator*(double scale, Physical ob1);
    friend Physical operator/(Physical ob1, double scale);
    friend Physical operator/(double scale, Physical ob1);
};

Physical operator+(Physical ob1, Physical ob2)
{
    Physical phy(ob1.size());
    for(unsigned i = 0; ob1.size(); i++)
    {
        phy[i] = ob1[i] + ob2[i];
    }

    return phy;
}

Physical operator-(Physical ob1, Physical ob2)
{
    Physical phy(ob1.size());
    for(unsigned i = 0; ob1.size(); i++)
    {
        phy[i] = ob1[i] - ob2[i];
    }

    return phy;
}

Physical operator*(Physical ob1, double scale)
{
    Physical phy(ob1.size());
    for(unsigned i = 0; ob1.size(); i++)
    {
        phy[i] = ob1[i] * scale;
    }

    return phy;
}

Physical operator*(double scale, Physical ob1)
{
    return ob1 * scale;
}

Physical operator/(Physical ob1, double scale)
{
    Physical phy(ob1.size());
    for(unsigned i = 0; ob1.size(); i++)
    {
        phy[i] = ob1[i] * scale;
    }

    return phy;
}

Physical operator/(double scale, Physical ob1)
{
    return ob1 / scale;
}


#endif // PHYSICAL_H


Компилируется и выдаёт следующие ошибки:
Цитата

g++ -enable-stdcall-fixup -Wl,-enable-auto-import -Wl,-enable-runtime-pseudo-reloc -shared -mthreads -Wl -Wl,--out-implib,debug\libsmartflowlib1.a -o debug\smartflowlib1.dll object_script.smartflowlib.Debug -L"d:\Qt\2009.05\qt\lib" debug\smartflowlib_resource_res.o ./libs/libboost_serialization.a ./libs/libLinAlg.a -lQtCored4
./debug\Solver.o: In function `Zpl8PhysicalS_':
d:/qt/2009.05/mingw/bin/../lib/gcc/mingw32/4.4.0/include/c++/new:101: multiple definition of `operator+(Physical, Physical)'
./debug\smartflowlib.o:D:\Qt\smart-flow\SmartFlowLib/Source/Physical.h:38: first defined here
./debug\Solver.o: In function `Zmi8PhysicalS_':
D:\Qt\smart-flow\SmartFlowLib/Source//Physical.h:49: multiple definition of `operator-(Physical, Physical)'
./debug\smartflowlib.o:D:\Qt\smart-flow\SmartFlowLib/Source/Physical.h:49: first defined here
./debug\Solver.o: In function `Zml8Physicald':
D:\Qt\smart-flow\SmartFlowLib/Source//Physical.h:60: multiple definition of `operator*(Physical, double)'
./debug\smartflowlib.o:D:\Qt\smart-flow\SmartFlowLib/Source/Physical.h:60: first defined here
./debug\Solver.o: In function `Zmld8Physical':
D:\Qt\smart-flow\SmartFlowLib/Source//Physical.h:71: multiple definition of `operator*(double, Physical)'
./debug\smartflowlib.o:D:\Qt\smart-flow\SmartFlowLib/Source/Physical.h:71: first defined here
./debug\Solver.o: In function `Zdv8Physicald':
D:\Qt\smart-flow\SmartFlowLib/Source//Physical.h:76: multiple definition of `operator/(Physical, double)'
./debug\smartflowlib.o:D:\Qt\smart-flow\SmartFlowLib/Source/Physical.h:76: first defined here
./debug\Solver.o: In function `Zdvd8Physical':
D:\Qt\smart-flow\SmartFlowLib/Source//Physical.h:87: multiple definition of `operator/(double, Physical)'
./debug\smartflowlib.o:D:\Qt\smart-flow\SmartFlowLib/Source/Physical.h:87: first defined here
./debug\Mesh.o: In function `Zpl8PhysicalS_':
d:/qt/2009.05/mingw/bin/../lib/gcc/mingw32/4.4.0/include/c++/new:101: multiple definition of `operator+(Physical, Physical)'
Creating library file: debug\libsmartflowlib1.a
mingw32-make[1]: Leaving directory `D:/Qt/smart-flow/SmartFlowLib'
mingw32-make: Leaving directory `D:/Qt/smart-flow/SmartFlowLib'
./debug\smartflowlib.o:D:\Qt\smart-flow\SmartFlowLib/Source/Physical.h:38: first defined here
./debug\Mesh.o: In function `Zmi8PhysicalS_':
D:\Qt\smart-flow\SmartFlowLib/Source//Physical.h:49: multiple definition of `operator-(Physical, Physical)'
./debug\smartflowlib.o:D:\Qt\smart-flow\SmartFlowLib/Source/Physical.h:49: first defined here
./debug\Mesh.o: In function `Zml8Physicald':

.......................

./debug\ImportGambit.o: In function `Zdv8Physicald':
D:\Qt\smart-flow\SmartFlowLib/Source/Imports//../Physical.h:76: multiple definition of `operator/(Physical, double)'
./debug\smartflowlib.o:D:\Qt\smart-flow\SmartFlowLib/Source/Physical.h:76: first defined here
./debug\ImportGambit.o: In function `Zdvd8Physical':
D:\Qt\smart-flow\SmartFlowLib/Source/Imports//../Physical.h:87: multiple definition of `operator/(double, Physical)'
./debug\smartflowlib.o:D:\Qt\smart-flow\SmartFlowLib/Source/Physical.h:87: first defined here
collect2: ld returned 1 exit status
mingw32-make[1]: *** [debug\smartflowlib1.dll] Error 1
mingw32-make: *** [debug] Error 2
Завершено с кодом возврата 2.
Ошибка во время сборки проекта SmartFlowLib
Во время выполнения сборки на этапе 'Make'


Якобы  multiple definition, хотя в подключаю это h-файл только в одном месте.  smile  smile  smile 

Заранее спасибо! 

Автор: MTWizard 18.1.2010, 23:21
Сделай операторы inline

Автор: Elfet 18.1.2010, 23:23
MTWizard,  smile  smile  smile  smile  smile  smile  smile  smile  smile  smile  smile  smile 

Автор: zim22 19.1.2010, 11:30
Цитата(Elfet @  18.1.2010,  21:57 Найти цитируемый пост)
class Physical : public vector<double>

Elfet, я бы на твоём месте использовал вектор в отношении "has-a" по отношению к твоему классу, а не "is-a".
т.е. так:
Код

class Physical {
  std::vector<double> vd;
};

***
Цитата(Elfet @  18.1.2010,  21:57 Найти цитируемый пост)
Physical operator+(Physical ob1, Physical ob2){    
  Physical phy(ob1.size());    
  for(unsigned i = 0; ob1.size(); i++)    {        
    phy[i] = ob1[i] + ob2[i];    
  }   
 return phy;
}

вечный цикл?
 for(unsigned i = 0; ob1.size(); i++)    {        

Автор: saneea 19.1.2010, 12:48
Можно было просто реализацию перегрузок операторов запихнуть в .cpp файл.

Автор: Earnest 20.1.2010, 20:23
Цитата(zim22 @  19.1.2010,  12:30 Найти цитируемый пост)
Elfet, я бы на твоём месте использовал вектор в отношении "has-a" по отношению к твоему классу, а не "is-a".

Elfet, прислушайся к этому совету. Наследовать стандартные контейнеры - очень дурной тон. 

Автор: Elfet 20.1.2010, 23:12
zim22, да, спасибо. Цикл поправлю. 

А в чём дурной? Мне то нужно было всего навсего что бы операции выполнялись + toString()

Автор: Earnest 21.1.2010, 08:11
Читай труды отцов типа Майерса. Вообще наследование от конкретного (не абстрактного) класса - это плохо в долгострочной перспективе (развития программы). Чтобы хорошенько проняло, надо поподдерживать какой-нибудь большой проект лет 5-10. А пока просто поверь и вырабатывай правильные привычки. Желание использовать готовую функциональность какого-либо класса - это совершенно недостаточный повод для наследования. Твой Physical - это не вектор даблов, он просто может быть построен на основе вектора даблов (а может и на чем-то другом). А это совсем другое дело.

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)