【发布时间】:2013-04-27 12:06:21
【问题描述】:
我有这个代码:
#include<iostream>
#include<string>
class Test
{
public:
std::string& GetText()
{
return text;
}
void Display() { std::cout << text << std::endl; }
private:
std::string text;
};
int main()
{
Test test;
test.GetText() = "Testing";
test.Display();
}
现在这个引用函数就像一个函数名下的 get 和 setter 一样工作。所以我想知道使用这种方法是否有益,或者使用单独的 get 和 set 方法是否更有益。或者将变量公开是否更有意义。
【问题讨论】:
-
让函数返回对成员变量的引用是可以的,但命名可能并不完美(恕我直言),因为您可以使用“get”函数来“设置”一个值。
标签: c++ methods properties get set