我正在编写C++代码,现在遇到一个困境。
编辑:我添加了相关类的定义
- _fullName 在类中被定义为私有 dm(char _fullName)
我的类包含以下getter方法:
char* getFullName() const { return this->_fullName; }
然而,我曾经遇到过这样的情况,即返回带有const修饰符的char*(const char*)
我可以将getter方法更改为以下内容:
const char* getFullName() const { return this->_fullName; }
两个版本都可以编译,但我不知道该怎么选择。 我会选择第二个版本,但我想知道为什么没有const关键字的版本也能编译?因为这是一个CONST成员函数,因此dms也是const,没有const关键字就不能返回dms吗?
这是相关类的定义:
class Professional
{
private:
char* _ID;
char* _fullName;
int _age;
char* _profession;
}
_fullName
的声明吗?它是char
还是char *
?如果它只是一个 char,那么你不能用 char * 或 const char * 作为返回类型来返回 _fullName。你需要返回 char 类型或者返回&this->_fullName
。 - code_fodder