我想排序的汽車價格在他們的數組,我似乎有一個問題排序數組是指向另一個類的指針。當我嘗試改變數組的順序時,我得到「錯誤C2106:'=':左操作數必須是l值」。C++排序數組是指向一個類的指針
我附上了下面的代碼。
我的排序功能。
void CarPool::Sort()
{
const int MAXVAL = 9;
int coun = countCars;
double temp;
bool swappedFlag = true;
while (swappedFlag)
{
swappedFlag = false;
for (int i = 0; i < countCars - 1; i++)
{
ptrToPool[i].getPrice();
if (ptrToPool[i].getPrice()> ptrToPool[i + 1].getPrice())
{
temp = ptrToPool[i].getPrice();
ptrToPool[i].getPrice() = ptrToPool[i + 1].getPrice(); //ERROR C2106
ptrToPool[i + 1].getPrice() = temp; //ERROR C2106
swappedFlag = true;
}
}
}
}
car.cpp
#pragma once
#include "car.h" // put the related header at the TOP of the list of includes
#include <string>
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
Car::Car(string mName, string reg, double eng, double pri)
{
// store the parameter values for this object private data
ModelName = mName;
Registration = reg;
EngineSize = eng;
Price = pri;
}
Car::Car()
{
// set up a value that shows the data not properly loaded
ModelName = "Unspecified";
}
void Car::Load(ifstream& carFile)
{
carFile>>ModelName>>Registration>>EngineSize>>Price;
}
void Car::Display()
{
cout<<setfill(' ')<<setw(10)<<ModelName<<setfill(' ')<<setw(10)<<Registration;
cout<<setfill(' ')<<setw(10)<<EngineSize<<setfill(' ')<<setw(10)<<Price<<endl;
}
double Car::Ratio() //how much it costs per cc of engine!
{
return EngineSize/Price;
}
string Car::getRegistration()
{
return Registration;
}
double Car::getPrice()
{
return Price;
}
carpool.cpp(也在第一代碼段中列出的功能)
#include "carpool.h"
#include <iostream>
#include <fstream>
using namespace std;
CarPool::CarPool()
{
countCars=0; //for now
name = "None";
}
CarPool::~CarPool()
{
if (countCars>0)
{
delete [] ptrToPool;
}
}
int CarPool::Load(string fromFilename)
{
// assumes file starts with count of cars
ifstream inFile(fromFilename);
if (!inFile)
{
return -1; //oh dear no file to read
}
inFile>>countCars; //read the following number of cars
ptrToPool = new Car[countCars];
for (int i=0; i<countCars; i++)
{
ptrToPool[i].Load(inFile);
}
return 0; //successful!
}
car.h
#pragma once
#include <string>
using namespace std;
class Car
{
public:
// see later for the bodies of the functions!
Car(string mName, string reg, double eng, double pri);
Car();
void Load(ifstream& carFile);
void Save(ofstream& carFile);
void Display();
string getRegistration();
double getPrice();
double Ratio(); //how much it costs per cc of engine!
void setPrice(double pri);
private:
string ModelName;
string Registration;
double EngineSize;
double Price;
};
你需要交換汽車本身,而不是價值。 「ptrToPool [i] = ptrToPool [i + 1];」等。另外,我強烈建議使用更多的標準庫函數。特別是,std :: sort會爲你完成大部分工作。您也可以使用std :: swap進行交換。你也可以使用std :: vector而不是數組。當你使用標準庫函數時,你的代碼往往更簡單,更快速,並且更無錯誤。 – Lalaland