【发布时间】:2021-11-26 16:00:46
【问题描述】:
目前,我正在尝试实现到目前为止所学的内容:C++ 中的 OOP 类。这里我有两个不同的类:VehicleInfo 和 Vehicle。下面是我写的代码:
#include <iostream>
#include <string>
#include <fstream>
#include <math.h>
#define M_PI 3.1416
using namespace std;
class VehicleInfo{
public:
string brand;
bool electric;
int catalogue_price;
float tax_percentage = 0.05;
VehicleInfo(string brand, bool electric, int catalogue_price){
VehicleInfo::brand = brand;
VehicleInfo::electric = electric;
VehicleInfo::catalogue_price = catalogue_price;
}
float compute_tax(){
if (VehicleInfo::electric == true){
tax_percentage = 0.02;
}
return VehicleInfo::catalogue_price * tax_percentage;
}
void print_vehicle_info(){
std::cout << "Brand : " << brand << std::endl;
std::cout << "Payable Tax : " << compute_tax() << std::endl;
}
};
class Vehicle{
public:
string id;
string license_plate;
VehicleInfo vehicle;
Vehicle(string id, string license_plate, VehicleInfo vehicle){
Vehicle::id = id;
Vehicle::license_plate = license_plate;
Vehicle::vehicle = vehicle;
}
string getName(){
return Vehicle::vehicle.brand;
}
int getTax(){
return Vehicle::vehicle.compute_tax();
}
void print_vehicle(){
std::cout << "ID : " << id << std::endl;
std::cout << "License Plate : " << license_plate << std::endl;
std::cout << "Brand : " << getName() << std::endl;
std::cout << "Tax : " << getTax() << std::endl;
}
};
int main(int argc, char const *argv[])
{
cout << endl;
VehicleInfo unit1 = VehicleInfo("Tesla Model 3", true, 60000);
unit1.print_vehicle_info();
Vehicle unit2 = Vehicle("YU2314", "KL0932", unit1);
unit2.print_vehicle();
std::cin.get();
return 0;
}
我对代码的期望是,Vehicle 类中的属性“vehicle”将使用 VehicleInfo 类中的属性和函数“compute_tax()”进行初始化。我收到的错误代码如下所示:
cohesion_coupling.cpp: In constructor 'Vehicle::Vehicle(std::__cxx11::string, std::__cxx11::string, VehicleInfo)':
cohesion_coupling.cpp:42:70: error: no matching function for call to 'VehicleInfo::VehicleInfo()'
Vehicle(string id, string license_plate, VehicleInfo vehicle){
^
cohesion_coupling.cpp:17:9: note: candidate: 'VehicleInfo::VehicleInfo(std::__cxx11::string, bool, int)'
VehicleInfo(string brand, bool electric, int catalogue_price){
^~~~~~~~~~~
cohesion_coupling.cpp:17:9: note: candidate expects 3 arguments, 0 provided
cohesion_coupling.cpp:10:7: note: candidate: 'VehicleInfo::VehicleInfo(const VehicleInfo&)'
class VehicleInfo{
^~~~~~~~~~~
cohesion_coupling.cpp:10:7: note: candidate expects 1 argument, 0 provided
cohesion_coupling.cpp:10:7: note: candidate: 'VehicleInfo::VehicleInfo(VehicleInfo&&)'
cohesion_coupling.cpp:10:7: note: candidate expects 1 argument, 0 provided
任何改进代码的建议(或者可能需要对我所做的课堂实践进行一些更正)?
【问题讨论】: