0

我正在为我的类 Vehicle 编写一个复制构造函数,但我无法访问该类在此构造函数中具有的数组。我使用点表示法(vehi.vin)设置了其他值,并且效果很好,正如预期的那样。所以我尝试使用相同的想法 vehi.accessories[0] 访问数组,但这似乎返回一个空值而不是实际存在的字符串。而且我知道当我第一次初始化类时,该数组确实包含正确的值,因为我可以将它们打印出来。所以我的问题是,我怎样才能从一个类中访问一个数组?我使用点表示法错误吗?我不能对数组使用点表示法吗?我只需要一个get方法吗?

代码 -

车辆.cpp

Vehicle::Vehicle(const Vehicle& vehi)
{
//get values and set them equal to the local object's attributes
vin = vehi.vin;

for(int i = 0; i < vehi.numAccessories; i++)
{
    //cout << "get here\n";
    accessories[i] = vehi.accessories[i];
    cout << accessories[i] << " " << vehi.accessories[i] << endl;
}
}

配饰如何获得价值:

for(int i = 0; i < numAccessories; i++) //loop through file until all accessories for the car have been put into the array
{
        getline(fin, accessories[i]); //put accessory in the next spot in the accessory array
        cout << "Accessory " << (i+1) << ": " << accessories[i] << endl;
}

车辆对象的 main.cpp 声明。构造函数使用传递给它的文件对象读取值。

Vehicle temp(fin);

车辆.h

private:
    string accessories[50]; //array of accessories stored in string form

编辑:当我尝试直接调用复制构造函数时,它工作正常,但是当调用 printVehicle() 函数时,它似乎到达了那里,但不知何故失败了。下面的代码做了我想要的,并向我展示了复制构造函数工作正常,所以我猜这是从 printVehicle() 调用它的方式

主.cpp:

Vehicle test(fin);
test.startAcc();
cout << endl << test.nextAcc() << endl;
Vehicle test2(test);
test2.startAcc();
cout << endl << test2.nextAcc() << endl;
4

0 回答 0