c++ - 打印奇怪的结果

标签 c++

为什么调用 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/

相关文章:

c++ - 为什么要将 DB 连接指针对象实现为引用计数指针? (C++)

c++ - 在链表的某个位置插入节点C++

c++ - 通信在线程中丢失

c++11 enable_if 错误 - 模板参数重新声明

c++ - 选择随机子集的通用算法实现

c++ - Poppler:以目标分辨率渲染

c++ - 无法在 C++ map 容器中输入正确的元素

c++ - std::bind 与 std::less_equal

c++ - 使用 std::mem_fun 时如何传递两个参数?

c++ - 用于模板特化的虚拟函数或 SFINAE ......或更好的方法?