You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++字符串字面量理解困惑及‘禁止将字符串常量转换为char*’错误修复咨询

Fixing the "C++ forbids converting a string constant to char*" Error in Your Bank Class Code

Hey, let's work through the issues in your code and get it running smoothly. That error you're seeing has two key causes, both tied to your constructor's strcpy call:

1. Reversed strcpy Parameters

The strcpy function follows the pattern strcpy(destination, source)—you've got the arguments backwards. Your original line strcpy("", name) tries to copy the contents of name into the string constant "", which is impossible because string constants are stored in read-only memory.

2. String Constants Are const char*

C++ strictly blocks implicit conversion of a string constant (const char*) to a non-const char* because it would let you modify read-only memory (a surefire way to trigger undefined behavior). When you pass "" as the first argument to strcpy (which expects a writable char*), that's exactly what you're attempting to do.


Fixed Code

Here's the corrected version of your code, with key changes highlighted:

#include <cstring>
#include <iostream>
using namespace std;

class Bank {
private:
    char name[20];
    int acc;
    float amount;
public:
    Bank() {
        // Fixed: swapped strcpy arguments to target 'name'
        strcpy(name, "");
        acc = 0;
        amount = 0;
    }
    void open(int a) {
        cout << "Enter name:";
        cin >> name;
        acc = a;
        cout << "Enter Amount" << endl;
        cin >> amount;
    }
    void edit(int flag, float a);
};

int main() {
    Bank B[10];
}

Bonus: A Safer C++ Alternative

If you want to avoid these C-style string headaches entirely, use std::string instead of a raw char array. It handles initialization, copying, and memory management automatically:

#include <iostream>
#include <string> // Add this header
using namespace std;

class Bank {
private:
    string name; // Use std::string instead of char array
    int acc;
    float amount;
public:
    Bank() : name(""), acc(0), amount(0.0f) {
        // No need for strcpy at all!
    }
    void open(int a) {
        cout << "Enter name:";
        cin >> name;
        acc = a;
        cout << "Enter Amount" << endl;
        cin >> amount;
    }
    void edit(int flag, float a);
};

int main() {
    Bank B[10];
}

This version eliminates the risk of buffer overflows and parameter mix-ups, which are common pitfalls with raw char arrays.

内容的提问来源于stack exchange,提问作者Usus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 11:24:10