为什么调用 c2.view() 会打印出客户 ID 的 ID 和名称?
我盯着这个看了一会儿,找不到原因。我要么错过了一些非常明显的东西,要么我不明白 cstrings 是如何工作的:)
客户.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
客户.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;
}
驱动.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 . . .
最佳答案
您正在传递一个包含七个字符的字符串:
char id[] = "123456"; // one more character for null termination '\0'
但您的数组大小为 6。因此,当您打印 accountId
时,您超出了 '6'
字符并打印出它旁边的任何内容,其中这种情况恰好是name
的内容。
使用 std::strings
代替字符数组可以省去很多麻烦。
关于c++ - 打印奇怪的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13594196/