假设我有以下内容:
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;}
};
答案 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
。