Вопрос задан 07.10.2026 в 14:17. Предмет Информатика. Спрашивает Андреев Игорь.

В коде выдает 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";
}
}

Перейти к ответам

Ответы на вопрос

Отвечает Степанова Валерия.

Обе ошибки возникают из-за того, что при вызове конструктора аргументы передаются не в том порядке.

Конструктор у вас объявлен так:

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

То есть он ожидает аргументы в таком порядке:

C++
int, int, int, std::string, float

А вызываете вы его так:

C++
new Commutator( rand() % 20 + 5, rand() % 4000 + 2000, rand() % 100 + 20, 0, manufacturers[manufacturerIndex] );

Фактически получается:

C++
int, int, int, int, std::string

То есть четвертым параметром вы передаете 0, хотя конструктор ожидает std::string, а пятым передаете строку, хотя там должен быть float.

Именно поэтому появляется ошибка:

C++
невозможно преобразовать аргумент 5 из "std::string" в "float"

Нужно поменять последние два аргумента местами:

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

Но использовать здесь new вообще не нужно. Более правильно написать просто:

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

В вашем варианте:

C++
*new Commutator(...)

создается объект в динамической памяти, затем он копируется в элемент массива, а созданный через new объект никогда не удаляется. Получается утечка памяти.

Цикл лучше записать так:

C++
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; }

Еще удобнее вообще не передавать цену в конструктор, если она всегда рассчитывается после создания объекта. Тогда конструктор можно сделать таким:

C++
Commutator(int portCounter_, int portSpeed_, int matrixSpeedCommunication_, std::string manufacturer_) { portCounter = portCounter_; portSpeed = portSpeed_; matrixSpeedCommunication = matrixSpeedCommunication_; manufacturer = manufacturer_; price = 0; }

И создавать объект так:

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

Таким образом, главная причина обеих ошибок — перепутаны местами manufacturer и price. Конструктор ожидает:

C++
..., std::string, float

а вы передавали:

C++
..., 0, std::string

Похожие вопросы

Топ вопросов за вчера в категории Информатика

Последние заданные вопросы в категории Информатика

Задать вопрос