【发布时间】:2022-08-04 19:08:52
【问题描述】:
#include<iostream>
#include<string>
using namespace std;
class Item{
private:
string type;
string abbrv;
string uID;
int aircraft;
double weight;
string destination;
public:
void print(){
cout << \"ULD: \" << type << endl;
cout << \"Abbreviation: \" << abbrv << endl;
cout << \"ULD-ID: \" << uID << endl;
cout << \"Aircraft: \" << aircraft << endl;
cout << \"Weight: \" << weight << \" Kilograms\" << endl;
cout << \"Destination: \" << destination << endl;
}
friend void kilotopound(Item);
};
void kilotopound(Item I){
cout << \"Weight in Pounds: \" << I.weight * 2.2 << \" LBS \" << endl;
}
int main(){
Item I;
I.type = \"Container\";
I.uID = \"AYK68943IB\";
I.abbrv = \"AYK\";
I.aircraft = 737;
I.weight = 1654;
I.destination = \"PDX\";
I.print();
kilotopound(I);
return 0;
}
从第 31 行开始,我收到错误 \'std::__cxxll::string Item::type\' is private in this context
我基本上是在尝试将此代码中的数据设为私有
class Item{
public:
string type;
string abbrv;
string uID;
int aircraft;
double weight;
string destination;
void print(){
cout << \"ULD: \" << type << endl;
cout << \"Abbreviation: \" << abbrv << endl;
cout << \"ULD-ID: \" << uID << endl;
cout << \"Aircraft: \" << aircraft << endl;
cout << \"Weight: \" << weight << \" Kilograms\" << endl;
cout << \"Destination: \" << destination << endl;
}
friend void kilotopound(Item);
};
void kilotopound(Item I){
cout << \"Weight in Pounds: \" << I.weight * 2.2 << \" LBS \" << endl;
}
int main(){
Item I;
I.type = \"Container\";
I.uID = \"AYK68943IB\";
I.abbrv = \"AYK\";
I.aircraft = 737;
I.weight = 1654;
I.destination = \"PDX\";
I.print();
kilotopound(I);
return 0;
}
任何帮助将不胜感激,我只是迷失了如何解决错误。谢谢!
此外,如果有人也可以提供帮助,我还需要能够再次复制和输出复制的数据,以及私人数据。再次感谢!
-
为了省去大家数数的麻烦,请指出哪一行是第31行。我想是这一行:
I.type = \"Container\"; -
private的目的是使类外的任何东西(例如main)都可以访问成员。如果您还想在课堂外访问成员,为什么还要让成员成为private? -
您的问题是
main()无法访问您班级的私人成员。与其尝试直接分配给私有类成员,不如添加可以设置或获取底层私有数据的公共成员函数(称为 setter 和 getter)。并提供可用于在创建类的实例时初始化成员的构造函数。