爲什麼調用c2.view()打印客戶ID的ID和名稱?打印奇怪的結果
我已經注視了這一段時間,並找不到原因。我要麼錯過了一些東西真的很明顯或者我不明白cstrings如何工作:)
Customer.h
#ifndef CUSTOMER_H
#define CUSTOMER_H
class Customer
{
private:
char accountID[6];
char name[30];
public:
Customer();
Customer(char[], char[]);
void view();
Customer operator=(const Customer&);
};
#endif
customer.cpp中
#include <string>
#include <iostream>
#include "Customer.h"
using namespace std;
Customer::Customer()
{
strcpy(accountID, "");
strcpy(name, "");
}
Customer::Customer(char acc[], char n[])
{
strcpy(accountID, acc);
strcpy(name, n);
}
void Customer::view()
{
cout << "Customer name: " << name << endl;
cout << "Customer ID: " << accountID <<endl;
}
Customer Customer::operator=(const Customer& right)
{
strcpy(accountID, right.accountID);
strcpy(name, right.name);
return* this;
}
Driver.cpp
#include <iostream>
#include "Customer.h"
using namespace std;
int main()
{
char id[] = "123456";
char n[] = "Bob";
Customer c1;
Customer c2(id, n);
c1.view();
c2.view();
system("pause");
return 0;
}
輸出:
Customer name:
Customer ID:
Customer name: Bob
Customer ID: 123456Bob
Press any key to continue . . .
使用'std :: string's。或者處理零終止的C字符串的痛苦。 – Mat
這是一個班級作業。我別無選擇,只能使用cstring :) – Zzz