• Предмет: Информатика
  • Автор: apelsinn00
  • Вопрос задан 5 месяцев назад

Помогите с кодом, выдает 2 ошибки: 1) отсутствуют экземпляры конструктора "Commutator::Commutator",соответствующий списку аргументов
2)"Commutator::Commutator(int,int,int,std::string,float)": невозможно преобразовать аргумент 5 из "std::string" в "float"
#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";
}
}
даю 50 баллов

Ответы

Ответ дал: vokerenjoyer
0

В определении конструктора Commutator в вашем коде есть неправильный параметр:

Commutator(int portCounter_, int portSpeed_, int matrixSpeedCommunication_, std::string manufacturer_, float price_)

{

portCounter = portCounter_;

portSpeed = portSpeed_;

matrixSpeedCommunication = matrixSpeedCommunication_;

price = price_;

manufacturer = manufacturer_;

}

В строке

commutatorArray[i] = *new Commutator(rand() % 20 + 5, rand() % 4000 + 2000, rand() % 100 + 20, 0, manufacturers [manufacturerIndex]);

вы пытаетесь вызвать конструктор с параметром 0, который передается в качестве аргумента manufacturer_. Но в определении конструктора этот параметр ожидает строку, а не число.

Чтобы исправить эту ошибку, вам нужно передать в качестве аргумента manufacturer_ строку, а не число 0. Например, вы можете использовать вместо 0 строку "unknown" или любую другую строку, которую считаете нужной:

commutatorArray[i] = *new Commutator(rand() % 20 + 5, rand() % 4000 + 2000, rand() % 100 + 20, "unknown", manufacturers [manufacturerIndex]);

После того как вы исправите эту ошибку, ваш код должен работать без ошибок.

Однако, я хотел бы отметить, что в вашем коде есть несколько элементов, которые могут быть улучшены. Например, вы используете устаревшую функцию rand() для генерации случайных чисел. Вместо этого вы можете использовать функции из стандартной библиотеки C++, такие как std::uniform_int_distribution и std::random_device, чтобы генерировать более случайные числа.

Также стоит отметить, что вы используете указатель new для создания экземпляра класса Commutator. Это не обязательно, так как вы можете создать экземпляр класса напрямую, без использования указателей:

commutatorArray[i] = Commutator(rand() % 20 + 5, rand() % 4000 + 2000, rand() % 100 + 20, "unknown", manufacturers [manufacturerIndex]);

Вас заинтересует