[英]How to Write Getters and Setters for C-Style String Array?
我不允許使用std::string
,並且需要使用C-Style
字符串數組。
我正在處理字符串數組的 Getter 和 Setter,但遇到以下錯誤:
錯誤:void Unit::SetName(const char*, unsigned int) 的原型與“Unit”類中的任何內容都不匹配
錯誤:候選是:void Unit::SetName(const char**, unsigned int)
下面是我的代碼片段。
#ifndef UNIT_H
#define UNIT_H
#include <iostream>
#include <string.h>
using namespace std;
const unsigned UnitNameSize = 10;
class Unit {
public:
Unit();
Unit( const char * nam, unsigned cred );
const char* GetName() const;
void SetName( const char *nam[], unsigned UnitNameSize);
friend ostream & operator <<( ostream & os, const Unit & U );
friend istream & operator >>( istream & input, Unit & U );
private:
char name[UnitNameSize];
int credits;
};
inline const char* Unit::GetName() const{
return name;
}
//error-ed set method
inline void Unit::SetName( const char* nam , unsigned namSize){
name[] = nam[namSize];
}
#endif
由於您班級中名稱的長度是固定長度,因此執行此操作的最簡單方法是std::strncpy
。 這將按如下方式工作:
inline void Unit::SetName (char const * name) {
std::strncpy(this->name, name, UnitNameSize);
// Ensure name member ends in null-terminator,
// even if new name length is >= UnitNameSize.
this->name[UnitNameSize - 1] = 0;
}
錯誤消息指出 SetName 的聲明和定義的簽名不匹配的事實。 在一個中,您期望指向另一個 ac 字符串中的 c 字符串的指針。 此外,您的 SetName 函數是錯誤的,它會嘗試通過參數字符串的末尾訪問字符。 為什么不能使用 std::string?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.