Char* getter 函数访问堆

问题描述 投票:0回答:1

假设我有会员:

char* name;

向该成员编写 getter 函数时,这是正确的方法吗:

char* getName(){
    return name;
}

但是当我们这样做时,现在这个类的用户可以在没有setter的情况下更改名称,因为用户拥有指向堆变量的指针。

我想到了这个解决方案:

char* getName(){
    char* otherName;
    otherName = new char[10];
    strcpy(otherName, name);
    return otherName;
}

但是现在,由于该函数创建了一个堆变量,用户可能会忘记删除该堆变量,这将是垃圾。这就是为什么这个实现也感觉不是为该成员实现 getter 函数的正确方法。

我该如何实施?

c++ oop getter-setter getter
1个回答
0
投票

如评论中所述,使用

std::string
而不是 char 数组。例如

class Person {
    std::string name;

public:
    Person(std::string name) : name(name) { }

    // When called on a const Person object,
    // we return a copy of the name.
    std::string get_name() const { return name; }

    // When called on a non-const Person object,
    // we return a reference, allowing name to be changed.
    std::string& get_name() { return name; }
};
© www.soinside.com 2019 - 2024. All rights reserved.