我非常喜欢C#中属性的概念,作为一个小小的项目,我一直在修改用C++实现它们的想法.我遇到了这个示例/sf/answers/414721611/这看起来相当不错,但我忍不住认为lambdas和非静态数据成员初始化可能会使用一些非常好的语法有这个想法.这是我的实现:
#include <iostream>
#include <functional>
using namespace std;
template< typename T >
class property {
public:
property(function<const T&(void)> getter, function<void(const T&)> setter)
: getter_(getter),
setter_(setter)
{};
operator const T&() {
return getter_();
};
property<T>& operator=(const T& value) {
setter_(value);
}
private:
function<const T&(void)> getter_;
function<void(const T&)> setter_;
};
class Foobar {
public:
property<int> num {
[&]() { return num_; },
[&](const int& value) { num_ = value; }
};
private:
int num_;
};
int main() {
// This …Run Code Online (Sandbox Code Playgroud) 我来自ActionScript 3等语言的背景,我们有一种特殊的方法可以将成员变量定义为实例和设置/获取受保护或私有成员值的方法.让我举个例子:
在课堂上,我们可以这样说:
private var _myString:String;
public get myString():String
{
return _myString;
}
public set myString(newValue:String):void
{
//Do some super secret member protection n' stuff
_myString = newValue;
}
Run Code Online (Sandbox Code Playgroud)
然后在该对象之外我可以执行以下操作:
trace(myClass.myString); //Output whatever _myString is. (note the lack of (). It's being accessed like property not a method...
Run Code Online (Sandbox Code Playgroud)
更进一步,我可以做一些像删除"public set myString"方法的东西,所以如果有人试图用我的类做这个:
myClass.myString = "Something"; //Try to assign - again note the lack of ()
Run Code Online (Sandbox Code Playgroud)
它会抛出一个错误,让用户知道该属性是以只读方式提供的.
既然我使用C++并且它比Actionscript 3更加出色,我想知道如何模仿这种行为.我不想使用一堆脏getVariable()和setVariable()方法.我希望通过一些操作符重载技巧我可以在这里完全相同的事情.注意我是菜鸟,所以请你这样说.:)
更新 我想最简单的解释方法是,我试图基本上有getter和setter但是通过赋值调用它们而不是用括号()来调用它们.
有一个Microsoft特定的扩展名,它使得可以这样定义属性获取器和设置器:
// declspec_property.cpp
struct S {
int i;
void putprop(int j) {
i = j;
}
int getprop() {
return i;
}
__declspec(property(get = getprop, put = putprop)) int the_prop;
};
int main() {
S s;
s.the_prop = 5;
return s.the_prop;
}
Run Code Online (Sandbox Code Playgroud)
有什么方法可以使用clang或gcc定义属性声明属性?如果我搜索__declspec,我发现的只是__declspec(dllexport),但我没有在寻找。
在我正在阅读的书中学习基本的c ++,有这个例子:
#include <iostream>
using namespace std;
class Point {
private: // Data members (private)
int x, y;
public: // Member functions
void set(int new_x, int new_y);
int get_x();
int get_y();
};
void Point::set(int new_x, int new_y) {
x = new_x;
y = new_y;
}
int Point::get_x() {
return x;
}
int Point::get_y() {
return y;
}
Run Code Online (Sandbox Code Playgroud)
我的问题是,在c ++中是否不可能在类本身中包含成员函数的定义?以上看起来相当混乱.书中说要定义一个类成员函数,你应该使用'return_type class_name :: function(){arguments}.但是在C#中你可以在同一个类中完成它而且代码更少.我在c ++中找不到很多关于属性的东西.感谢帮助.