我试图将位于_name中的字符数组传递给名为name的char引用。
但是,当将数组指针传递给引用时,它只显示第一个字符而不是整个字符串。
我的问题是你如何创建一个Character引用数组来将原始指针复制到它然后显示它?如item.cpp中所示,我们将_name指针复制到name的引用中,然后返回name,但它只显示字符串的第一个字符。
我只会显示我的代码的相关部分。
输出:
456: **A**
Qty: 0
Cost (price * tax): 200.00
567: **B**
Qty: 50
Cost (price * tax): 300.00
Enter Item info for A: (Enter 123 for sku)
sku: 123
name (no spaces): andrew
qty: 5
is taxed? (1/0): 1
price: 15
Copying A in C ----
123: a
Qty: 5
Cost (price * tax): 200.00
Saving A---------
Loading B----------
A: ----------
123: a
Qty: 5
Cost (price * tax): 200.00
B: ----------
123: a
Qty: 5
Cost (price * tax): 300.00
C=B; op=----------
123: a
Qty: 5
Cost (price * tax): 300.00
Operator ==----------
op== is NOT OK
op+=: A += 20----------
123
123: a
Qty: 5
Cost (price * tax): 200.00
op-=: A -= 10----------
123
123: a
Qty: 5
Cost (price * tax): 200.00
op+=double: ----------
1000.00=0.00
注意它是如何切断我的名字(andrew)并只显示一个?
Item.cpp:
void Item::name(const char * name){
strncpy(_name, name , 20);
}
const char& Item::name() const{
char& name = *_name;
return name;
}
ItemTester.cpp:
主():
int main(){
double res, val = 0.0;
fstream F;
SItem Empty;
SItem A("456", "AItem", 200);
SItem B("567", "BItem", 300, false);
//cout << A.name() << endl;
B.quantity(50);
//cout << Empty << endl;
cout << A << endl << B << endl << endl;
cout << "Enter Item info for A: (Enter 123 for sku)" << endl;
cin >> A;
cout << "Copying A in C ----" << endl;
SItem C = A;
cout << C << endl << endl;
cout << "Saving A---------" << endl;
A.save(F);
cout << "Loading B----------" << endl;
B.load(F);
cout << "A: ----------" << endl;
cout << A << endl << endl;
cout << "B: ----------" << endl;
cout << B << endl << endl;
cout << "C=B; op=----------" << endl;
C = B;
cout << C << endl << endl;;
cout << "Operator ==----------" << endl;
cout << "op== is " << ((A == "123") && !(A == "234") ? "OK" : "NOT OK") << endl << endl;
cout << "op+=: A += 20----------" << endl;
A += 20;
cout << A << endl << endl;
cout << "op-=: A -= 10----------" << endl;
A -= 10;
cout << A << endl << endl;
cout << "op+=double: ----------" << endl;
res = val += A;
cout << res << "=" << val << endl << endl;
return 0;
}
ostream写
virtual std::ostream& write(std::ostream& os, bool linear)const{
return os << sku() << ": " << name() << endl
<< "Qty: " << quantity() << endl
<< "Cost (price * tax): " << fixed << setprecision(2) << cost();
}
如果我错过了任何重要的细节并且用它来编辑我的帖子,请告诉我。