将一个字符数组传递给函数c ++

时间:2011-04-14 15:54:29

标签: c++ arrays

假设我有以下内容:

char cipan[9];

然后我应该传递给该函数? get和set方法怎么样?

我目前正在这样做

设置方法

void setCipan(char cipan[]){

this->cipan = cipan;
}

和get方法

char getCipan(){
return cipan;
}

编译时遇到错误?

我完全模糊..有人可以解释我应该传递给函数吗?

    class userData{
private:
    string name;
    char  dateCreate[9];

    void userDataInput(string name,char dateCreate[]){
        this->name = name;
        this->dateCreate = dateCreate;

    }
public:
    //constructor
    userData(string name){
        userDataInput(name,dateCreate);
    }
    userData(string name,char dateCreate[]){
        userDataInput(name,dateCreate);
    }
    //mutator methods
    void changeName(string name){this->name = name;}
    void changeDateCreate(char *dateCreate){this->dateCreate = dateCreate;}
    //accesor methods
    string getName(){return name;}
    char *getDateCreate(){return dateCreate;}


};

2 个答案:

答案 0 :(得分:1)

我会做以下事情:

void setCipan(const char* new_cipan)
{
    strcpy(cipan, new_cipan);
}

const char* getCipan() const
{
    return cipan;
}

当然,更好的方法是使用std::string

void setCipan(const string& new_cipan)
{
    cipan = new_cipan;
}

string getCipan() const
{
    return cipan;
}

答案 1 :(得分:1)

  • 构造函数的目的是初始化类变量。我认为没有必要在构造函数中调用另一个方法来进行初始化。


void userDataInput(string name,char dateCreate[]){
    this->name = name;
    this->dateCreate = dateCreate; // Both the dateCreate are class variables.
}

userData(string name){
    userDataInput(name,dateCreate); // dateCreate is already a class variable.
}

dateCreate是类范围变量。您只是将它传递给方法,并将其重新分配给dateCreate。赋值操作不会将一个数组的元素复制到另一个数组,并且是无效操作。

要复制数组元素,请改用std::copy