【发布时间】:2015-06-11 08:53:10
【问题描述】:
我正在尝试对包含价格的汽车数组进行排序,我似乎在对指向另一个类的指针的数组进行排序时遇到问题。当我尝试更改数组的顺序时,我得到“错误 C2106:'=':左操作数必须是左值”。
我附上了下面的代码。
我的排序功能。
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;
}
}
}
}
汽车.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!
}
汽车.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 代替数组。当您使用标准库函数时,您的代码往往会更简单、更快且更无错误。
标签: c++ arrays class sorting pointers