在C ++中为参数创建Set/Get函数 [英] Create Set/Get function to parameter in C++
本文介绍了在C ++中为参数创建Set/Get函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
大家好.
如何为变量创建get/set函数,如下所示:
Hi all.
how to create get/set function to variables as below:
class A{
Private:
char * m_sPathFile;
char *m_fileName;
};
感谢
thanks
推荐答案
请注意,C++
关键字为private
,全部为小写.
一般来说,您可以通过以下方式提供此类访问器:
Please note, theC++
keyword isprivate
, all lowercase.
General speaking you provide the such accessors this way:
class A
{
// members are 'automatically' private by default
int a;
// you explicitely declare the public section
public:
// ..
int get(){return a;}
void set(int n){a=n;}
};
我故意选择了int
数据成员 ,因为直接处理char指针有点棘手(例如,您是否需要字符串的副本或什么?),并且可能会更好.使用std::string
代替.
I chose a int
data member on purpose, because direct handling of char pointers is a bit tricky (for instance do you need a copy of the string or what?) and probably you''ll better use std::string
instead.
如果您使用的是Visual Studio,另一种方法是使用
__declspec及其属性属性.这将使您的设置者和获取者自动
属性(C ++)
If you are using Visual Studio the other way to do it is by using
__declspec and his property attribute. This will make you the setters and getters automatically
property (C++)
class A{
Private:
string m_strPathFile;
string m_strFileName;
Public:
void SetPathFile(string strPathFile);
string GetPathFile();
};
void A::SetPathFile(string strPathFile)
{
m_sPathFile = strPathFile;
}
string A::GetPathFile()
{
return m_strPathFile;
}
这篇关于在C ++中为参数创建Set/Get函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文