目录
通用的方式
C#的语法中自带类属性的get和set方式,可以很优雅的读写属性.在C++中要是向使用,通俗的写法是写内联函数,{C++在类的内部实现的函数默认为内联函数}
例如:
class MyClass
{
public:
int GetValue() { return _value; }
void SetValue(int num) { _value = num; }
string GetStrValue() { return _strValue; }
void SetValue(string str) { _strValue = str; }
private:
int _value;
string _strValue;
};
这是最简单的,也是最通用的不区分平台.
Windows平台方式:
在Windows系统下使用VS IED有种方式可以实现和C#属性的用法类似的方式:
属性 (C++) | Microsoft Docs 微软的文档
属性 (C++)
Microsoft 专用
此特性可应用于类或结构定义中的非静态“虚拟数据成员”。 编译器通过将这些“虚拟数据成员”的引用更改为函数调用来将其作为数据成员处理。
注意:
第一个类是普通的类,只要在通用的方式添加两行代码就可以实现
__declspec(property(get = GetValue, put = SetValue)) int value;
__declspec(property(get = GetStrValue, put = SetValue)) string strValue;
这行语法的内容是,只有 __declspec(property(get = GetValue, put = SetValue)) int value;
红色的你自己写的内联函数,紫色的是定义的属性,也就是你读写的时候的值;
用法:
MyClass myc;
myc.value = 10;
myc.strValue = "hello world";
cout << myc.value << endl;
cout << myc.strValue << endl;
使用类模板的方式:
template <typename T>
class MyTempClass
{
public:
T GetValue() { return _value; }
void SetValue(T num) { _value = num; }
__declspec(property(get = GetValue, put = SetValue)) T value;
private:
T _value;
};
用法:
MyTempClass<int> Mytc;
Mytc.value = 20;
cout << Mytc.value << endl;
MyTempClass<string> strMytc;
strMytc.value = "qwert";
cout << strMytc.value << endl;
MyTempClass<double> dMytc;
dMytc.value = 3.1415;
cout << dMytc.value << endl;
实验代码:
// CppGetSet.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
class MyClass
{
public:
int GetValue() { return _value; }
void SetValue(int num) { _value = num; }
string GetStrValue() { return _strValue; }
void SetValue(string str) { _strValue = str; }
__declspec(property(get = GetValue, put = SetValue)) int value;
__declspec(property(get = GetStrValue, put = SetValue)) string strValue;
private:
int _value;
string _strValue;
};
template <typename T>
class MyTempClass
{
public:
T GetValue() { return _value; }
void SetValue(T num) { _value = num; }
__declspec(property(get = GetValue, put = SetValue)) T value;
private:
T _value;
};
int main()
{
MyClass myc;
myc.value = 10;
myc.strValue = "hello world";
cout << myc.value << endl;
cout << myc.strValue << endl;
MyTempClass<int> Mytc;
Mytc.value = 20;
cout << Mytc.value << endl;
MyTempClass<string> strMytc;
strMytc.value = "qwert";
cout << strMytc.value << endl;
MyTempClass<double> dMytc;
dMytc.value = 3.1415;
cout << dMytc.value << endl;
return 0;
}
结果:
自己的想法:
虽然说这种方式很好用,但是个人认为并不是很好.因为这个方法只适用于Windows平台,要是使用跨平台的时候是不可以的,若只是在Windows平台下用,这个方式很是很值得推荐的,但是要是在Linux平台下使用,可能会编译过不(没有试过,).