我有一个作业,我无法编辑两个头文件,car.h和compass.h。在文件car.h中,有一个名为的私有函数:
void load_car();
。这稍后在car.cpp中定义为:
void car::load_car(){
cout << "Please enter make and model:" << endl;
ifstream inFile;
string fileName;
fileName = (make + "-" + model + ".txt");
inFile.open(fileName.c_str());
//not a finished function
}
我的问题是我有一个主要功能,
int main() {
cin >> make >> model;
car a(make, model);
a.load_car();
return 0;
}
我无法调用对象的私有成员函数。如何在不改变car.h标题的情况下正确执行此操作。任何帮助将不胜感激。
使用g ++编译时收到的错误是:
In file included from car.cpp:2:0:
car.h: In function ‘int main()’:
car.h:22:7: error: ‘void car::load_car()’ is private
void load_car();
^
car.cpp:14:13: error: within this context
a.load_car();
^
完整代码包含在下面: car.cpp
#include "compass.h"
#include "car.h"
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
string make, model;
int main() {
cin >> make >> model;
car a(make,model);
a.load_car();
return 0;
}
void car::load_car(){
cout << "Please enter make and model:" << endl;
ifstream inFile;
string fileName;
fileName = (make + "-" + model + ".txt");
inFile.open(fileName.c_str());
}
car.h
#ifndef CAR_H
#define CAR_H
#include <string>
#include "compass.h"
//Relative direction
enum class rDir {left, right};
class car
{
private:
std::string make, model;
int topSpeed, horsepower, mass;
double currentSpeed = 0;
//Defined by compass.h: an x/y coordinate struct and cardinal direction.
coordinates position;
compass direction;
//Helper functions
void load_car();
void update_position();
public:
//Constructor/Destructor
car (std::string ma, std::string mo) : make (ma), model (mo) {load_car();}
~car() {};
//Getters
std::string get_make() {return make;}
std::string get_model() {return model;}
coordinates get_position() {return position;}
compass get_direction() {return direction;}
double get_speed() {return currentSpeed;}
//Things cars do
void accelerate();
void brake();
void coast();
void steer (rDir turn);
};
#endif // CAR_H
答案 0 :(得分:2)
如果您不允许修改car.h,则无法从a.load_car()
致电main
。
如果您不允许修改main
,则说明您的作业不正确。
如果您要创建自己的main
,请在不致电a.load_car()
的情况下找到完成作业的方法。
答案 1 :(得分:0)
正如黑暗所提到的,load_car()函数是通过构造函数调用的,因此不应该在main()函数中调用。