C++ 如何为类成员变量编写setter?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15383167/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to write setter for class member variable?
提问by DevCoder
I'm trying to write a simple class in c++ with getter and setter for a class member variable. The getter works fine, but I cant write the setter. Is it possible to overwrite the "m_var" with a setter or is this only for pointer-variables possible?
我正在尝试用 getter 和 setter 用 C++ 编写一个简单的类,用于类成员变量。getter 工作正常,但我无法编写 setter。是否可以使用 setter 覆盖“m_var”,还是仅适用于指针变量?
class Foo: public QObject {
Q_OBJECT
public:
MyOtherClass& getVar() {
return m_var;
}
private:
MyOtherClass m_var;
};
回答by Laurent
this should be like that :
这应该是这样的:
// this is your setter
// you can set the var parameter as const because it is just copied to var
void setVar(const MyOtherClass& var){m_var = var;}
//this is your getter
MyOtherClass& getVar() {return m_var;}
// also this getter should be declared as const because you return a copy
// of m_var and thus you do not modify the object
MyOtherClass getVarByCopy() const {return m_var;}
the following code compiles fine with g++ :
下面的代码用 g++ 编译得很好:
class A
{
public :
int someInt;
};
class B{
A m_var;
public:
void setVar(const A& var){m_var = var;}
A& getVar() {return m_var;}
};
int main(int argc, char* argv[])
{
B b;
A a;
a = b.getVar();
b.setVar(a);
return 0;
}
回答by elimad
Are we missing something?
我们错过了什么吗?
class Foo: ...
{
.....
.....
MyOtherClass& getVar() {
return m_var;
}
Your
您的
getVar()
is actually a setter as it returns a non-const reference.
实际上是一个 setter,因为它返回一个非常量引用。
check this code.
检查此代码。
class MyOtherClass
{
public:
MyOtherClass(int i=10)
{
m_someInt = i;
}
int m_someInt;
};
class QObject
{
};
class Foo: public QObject
{
// Q_OBJECT
public:
MyOtherClass& getVar()
{
return m_var;
}
private:
MyOtherClass m_var;
};
void someFunc()
{
Foo f1;
printf("%d", f1.getVar().m_someInt);
f1.getVar() = 100;
printf("\r\n %d", f1.getVar().m_someInt);
}
Though i dont like the idea of such design.
If you really want getVar() to only get but not set, then it should be
虽然我不喜欢这种设计的想法。
如果你真的希望 getVar() 只获取而不设置,那么它应该是
const MyOtherClass& getVar()const {
return m_var;
}