C++字符串字面量理解困惑及‘禁止将字符串常量转换为char*’错误修复咨询
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

