В коде выдает 2 ошибки: 1) отсутствуют экземпляры конструктора "Commutator::Commutator", соответствующий списку аргументов
2) "Commutator::Commutator(int,int,int,std::string,float)": невозможно преобразовать аргумент 5 из "std::string" в "float"
#include
#include
#include
#include
#include
#include
const int N = 10;
class Commutator
{
public:
int portCounter;
int portSpeed;
int matrixSpeedCommunication;
float price;
std::string manufacturer;
Commutator()
{
};
Commutator(int portCounter_, int portSpeed_, int matrixSpeedCommunication_,
std::string manufacturer_, float price_)
{
portCounter = portCounter_;
portSpeed = portSpeed_;
matrixSpeedCommunication = matrixSpeedCommunication_;
price = price_;
manufacturer = manufacturer_;
}
};
int main()
{
std::string manufacturers[] = { "name1","name2","name3" };
srand(time(nullptr));
Commutator commutatorArray[N];
for (int i = 0; i < N; ++i)
{
int manufacturerIndex = rand() % 3;
commutatorArray[i] = *new Commutator(rand() % 20 + 5, rand() % 4000 + 2000, rand() % 100 + 20, 0,
manufacturers [manufacturerIndex]);
commutatorArray[i].price = commutatorArray[i].portCounter * 2.0 + commutatorArray[i].matrixSpeedCommunication * 1.5 + commutatorArray[i].portSpeed * 1.2;
std::cout << "[" << i << "] " << commutatorArray[i].manufacturer <<";" << commutatorArray[i].portCounter << "; " << commutatorArray[i].matrixSpeedCommunication
<< "; " << commutatorArray[i].portSpeed << "; " << commutatorArray[i].price << "\n";
}
Commutator bestPriceArray[N];
Commutator bestPortCounter[N];
std::copy(commutatorArray, commutatorArray + N, bestPriceArray);
std::copy(commutatorArray, commutatorArray + N, bestPortCounter);
//Sort by price
std::sort(bestPriceArray, bestPriceArray + N, [](const Commutator& a, const Commutator& b) -> bool
{
return a.price > b.price;
});
//Sort by portNumber
std::sort(bestPortCounter, bestPortCounter + N, [](const Commutator& a, const Commutator& b) -> bool
{
return a.portCounter < b.portCounter;
});
std::cout << "Best price:\n";
for (int i = 1; i < 6; ++i)
{
std::cout << "[" << i << "] " << bestPriceArray[N - i].portCounter << "; " << bestPriceArray[N - i].matrixSpeedCommunication << "; " << bestPriceArray[N - i].portSpeed << "; " << bestPriceArray[N - i].price << "\n";
}
std::cout << "Best port counter:\n";
for (int i = 1; i < 6; ++i)
{
std::cout << "[" << i << "] " << bestPortCounter[N - i].portCounter << "; " << bestPortCounter[N - i].matrixSpeedCommunication << "; " << bestPortCounter[N - i].portSpeed << "; " << bestPortCounter[N - i].price << "\n";
}
}
#include
#include
#include
#include
#include
const int N = 10;
class Commutator
{
public:
int portCounter;
int portSpeed;
int matrixSpeedCommunication;
float price;
std::string manufacturer;
Commutator()
{
};
Commutator(int portCounter_, int portSpeed_, int matrixSpeedCommunication_,
std::string manufacturer_, float price_)
{
portCounter = portCounter_;
portSpeed = portSpeed_;
matrixSpeedCommunication = matrixSpeedCommunication_;
price = price_;
manufacturer = manufacturer_;
}
};
int main()
{
std::string manufacturers[] = { "name1","name2","name3" };
srand(time(nullptr));
Commutator commutatorArray[N];
for (int i = 0; i < N; ++i)
{
int manufacturerIndex = rand() % 3;
commutatorArray[i] = *new Commutator(rand() % 20 + 5, rand() % 4000 + 2000, rand() % 100 + 20, 0,
manufacturers [manufacturerIndex]);
commutatorArray[i].price = commutatorArray[i].portCounter * 2.0 + commutatorArray[i].matrixSpeedCommunication * 1.5 + commutatorArray[i].portSpeed * 1.2;
std::cout << "[" << i << "] " << commutatorArray[i].manufacturer <<";" << commutatorArray[i].portCounter << "; " << commutatorArray[i].matrixSpeedCommunication
<< "; " << commutatorArray[i].portSpeed << "; " << commutatorArray[i].price << "\n";
}
Commutator bestPriceArray[N];
Commutator bestPortCounter[N];
std::copy(commutatorArray, commutatorArray + N, bestPriceArray);
std::copy(commutatorArray, commutatorArray + N, bestPortCounter);
//Sort by price
std::sort(bestPriceArray, bestPriceArray + N, [](const Commutator& a, const Commutator& b) -> bool
{
return a.price > b.price;
});
//Sort by portNumber
std::sort(bestPortCounter, bestPortCounter + N, [](const Commutator& a, const Commutator& b) -> bool
{
return a.portCounter < b.portCounter;
});
std::cout << "Best price:\n";
for (int i = 1; i < 6; ++i)
{
std::cout << "[" << i << "] " << bestPriceArray[N - i].portCounter << "; " << bestPriceArray[N - i].matrixSpeedCommunication << "; " << bestPriceArray[N - i].portSpeed << "; " << bestPriceArray[N - i].price << "\n";
}
std::cout << "Best port counter:\n";
for (int i = 1; i < 6; ++i)
{
std::cout << "[" << i << "] " << bestPortCounter[N - i].portCounter << "; " << bestPortCounter[N - i].matrixSpeedCommunication << "; " << bestPortCounter[N - i].portSpeed << "; " << bestPortCounter[N - i].price << "\n";
}
}
Ответы на вопрос
Обе ошибки возникают из-за того, что при вызове конструктора аргументы передаются не в том порядке.
Конструктор у вас объявлен так:
Commutator(int portCounter_,
int portSpeed_,
int matrixSpeedCommunication_,
std::string manufacturer_,
float price_)То есть он ожидает аргументы в таком порядке:
int, int, int, std::string, floatА вызываете вы его так:
new Commutator(
rand() % 20 + 5,
rand() % 4000 + 2000,
rand() % 100 + 20,
0,
manufacturers[manufacturerIndex]
);Фактически получается:
int, int, int, int, std::stringТо есть четвертым параметром вы передаете 0, хотя конструктор ожидает std::string, а пятым передаете строку, хотя там должен быть float.
Именно поэтому появляется ошибка:
невозможно преобразовать аргумент 5 из "std::string" в "float"Нужно поменять последние два аргумента местами:
commutatorArray[i] = *new Commutator(
rand() % 20 + 5,
rand() % 4000 + 2000,
rand() % 100 + 20,
manufacturers[manufacturerIndex],
0.0f
);Но использовать здесь new вообще не нужно. Более правильно написать просто:
commutatorArray[i] = Commutator(
rand() % 20 + 5,
rand() % 4000 + 2000,
rand() % 100 + 20,
manufacturers[manufacturerIndex],
0.0f
);В вашем варианте:
*new Commutator(...)создается объект в динамической памяти, затем он копируется в элемент массива, а созданный через new объект никогда не удаляется. Получается утечка памяти.
Цикл лучше записать так:
for (int i = 0; i < N; ++i)
{
int manufacturerIndex = rand() % 3; commutatorArray[i] = Commutator(
rand() % 20 + 5,
rand() % 4000 + 2000,
rand() % 100 + 20,
manufacturers[manufacturerIndex],
0.0f
);
commutatorArray[i].price =
commutatorArray[i].portCounter * 2.0f +
commutatorArray[i].matrixSpeedCommunication * 1.5f +
commutatorArray[i].portSpeed * 1.2f;
}
Еще удобнее вообще не передавать цену в конструктор, если она всегда рассчитывается после создания объекта. Тогда конструктор можно сделать таким:
Commutator(int portCounter_,
int portSpeed_,
int matrixSpeedCommunication_,
std::string manufacturer_)
{
portCounter = portCounter_;
portSpeed = portSpeed_;
matrixSpeedCommunication = matrixSpeedCommunication_;
manufacturer = manufacturer_;
price = 0;
}И создавать объект так:
commutatorArray[i] = Commutator(
rand() % 20 + 5,
rand() % 4000 + 2000,
rand() % 100 + 20,
manufacturers[manufacturerIndex]
);Таким образом, главная причина обеих ошибок — перепутаны местами manufacturer и price. Конструктор ожидает:
..., std::string, floatа вы передавали:
..., 0, std::stringПохожие вопросы
Топ вопросов за вчера в категории Информатика
Последние заданные вопросы в категории Информатика
-
Математика
-
Литература
-
Алгебра
-
Русский язык
-
Геометрия
-
Английский язык
-
Химия
-
Физика
-
Биология
-
Другие предметы
-
История
-
Обществознание
-
Окружающий мир
-
География
-
Українська мова
-
Информатика
-
Українська література
-
Қазақ тiлi
-
Экономика
-
Музыка
-
Право
-
Беларуская мова
-
Французский язык
-
Немецкий язык
-
МХК
-
ОБЖ
-
Психология
-
Физкультура и спорт
-
Астрономия
-
Кыргыз тили
-
Оʻzbek tili

