【问题标题】:assigning a const char array to a char array将 const char 数组分配给 char 数组
【发布时间】:2014-07-17 02:46:09
【问题描述】:

所以我有一个类 Mail,它有一个类数据成员 char type[30];和静态 const char FIRST_CLASS[];在类定义之外,我将 FIRST_CLASS[] 初始化为“First Class”。

在我的默认邮件构造函数中,我想将类型设置为 FIRST_CLASS[],但似乎无法找到这样做的方法。这是代码(有点精简,以免打扰您不需要的东西)

#include "stdafx.h"
#include <iostream>
#include <iomanip>   
#include <cstring>
#include <string>

using namespace std;
class Mail
{
public:
    Mail();
    Mail(const char* type, double perOunceCost, int weight);
    Mail(const Mail& other);

    ~Mail()
    { }

private:
    static const int TYPE_SIZE = 30;
    static const char FIRST_CLASS[];
    static const double FIXED_COST;
    static const int DEFAULT_WEIGHT = 1;

    char type[TYPE_SIZE];
    int weight;
    double perOunceCost;
};

const char Mail::FIRST_CLASS[] = "First Class";
const double Mail::FIXED_COST = 0.49;

// default
Mail::Mail()
{
    weight = DEFAULT_WEIGHT;
    perOunceCost = FIXED_COST;
    type = FIRST_CLASS;
}

这是错误:

1   error C2440: '=' : cannot convert from 'const char [12]' to 'char [30]'
2   IntelliSense: expression must be a modifiable lvalue

【问题讨论】:

  • @RakibulHasan 更新了错误,感谢提醒
  • 你为什么使用数组?为什么不使用std::string

标签: c++ arrays char cstring c-strings


【解决方案1】:

您不能将一个数组分配给另一个数组。试试strcpy

 strcpy(type,FIRST_CLASS);

确保 destination 至少与 source 一样大。

注意:如果不是强制性的,你应该避免使用数组,而将std::string用于字符数组和其他STL容器(vectormap..等)。

【讨论】:

  • 最好将type改为std::string
【解决方案2】:

您得到的错误不是因为您试图将 const char 数组分配给 char 数组(但是 - 这将是一个错误)。您报告的错误是因为您尝试将大小为 12 的数组(“First Class”是 12 个字符长)分配给大小为 30 的数组。即使两个数组都是 const,您也会收到相同的错误,或者非常量。

因为这是 C++ 而不是 C,就像其他人建议的那样,您应该使用 std::string。这是您使用 std::string 而不是 char 数组的示例。

#include <string>

using namespace std;
class Mail
{
public:
    Mail();
    Mail(string type_, double perOunceCost_, int weight_);

private:
    static const int TYPE_SIZE = 30;
    static const string FIRST_CLASS;
    static const double FIXED_COST;
    static const int DEFAULT_WEIGHT = 1;

    string type;
    int weight;
    double perOunceCost;
};

const string Mail::FIRST_CLASS("First Class");
const double Mail::FIXED_COST = 0.49;

// default
Mail::Mail()
{
    weight = DEFAULT_WEIGHT;
    perOunceCost = FIXED_COST;
    type = FIRST_CLASS;
}


Mail::Mail(string type_, double perOunceCost_, int weight_) :
    type(move(type_)),
    weight(weight_),
    perOunceCost(perOunceCost_)
{}

【讨论】:

  • 为什么尾随下划线?另外最好传递 const string& (for const char*)。
  • @zoska 假设您指的是构造函数,您是否错过了我移动字符串的事实?这里没有额外的副本。
  • 你仍然复制字符串作为参数传递给构造函数
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多