1

好的,所以我正在尝试为我在 C++ 中的类创建类似于 C# 中的属性的东西。

例如。在 C# 中我会这样做:

int MaxHP { get; set; }

或者,带有支持字段:

int MaxHP 
{ 
    get { return maxHP; }
    set { maxHP = value; }
}

但是到目前为止,使用 C++,我只能通过以下方式复制它:

private:    
    int maxHP;  
    int maxEP;
public:
    int GetMaxHP() { return maxHP; }
    void UpSetMaxHP(int value){ maxHP += value; }
    void DownSetMaxHP(int value){ maxHP -= value; }
    int GetMaxEP(){ return maxEP; }
    void UpSetMaxEP(int value){ maxEP += value; }
    void DownSetMaxEP(int value){ maxEP -= value; }

我必须在设计事物的方式上遗漏一些东西。在 C# 中,该属性将像字段一样访问。但是在 C++ 中,我必须执行从其他对象访问时工作方式不同的函数。

我想我可以这样做:

public:
    int MaxHP;

但这感觉就像我有点违背了目的。所以我的问题是,我这样做是对的还是有更好、更正确的方法来实现这一点?

4

4 回答 4

2

Rather than creating separate getter and setter functions, you can have a function which returns a reference which can be used either way:

public:   
    int &max_hp() { return maxHP; }

Unlike just delaring maxHP public, this allows you to place a breakpoint to see when the variable is accessed, and if you later want to add conditions or logging you can do so without changing your class interface.

于 2013-03-15T23:55:02.500 回答
1

This feature does not exist in C/C++. You could easily argue that it's a defect to be missing but not all languages are equal. The one thing Java has that C# doesn't is singleton object-like enums. It's otherwise, IMO, a bit of a dated language, but it still has one solid feature that's missing in C#.

So what I'm saying is, when you run into these things, often you do find a genuine weakness or a design flaw. It's good to ask if you're just missing something (hence my upvote) but as you learn what strengths and weaknesses different languages have, you'll learn which languages are good for which jobs and perhaps be effective at writing DSLs or language extensions earlier in your career than later.

于 2013-03-15T23:37:48.203 回答
0

To get rid of getters and setters functions in C++, I have written a simple macro that gets and sets most of data types that I use in my software. Templates also can be useful for that. For example

#define GET_BOOL(name) bool is##name() const {return name##_;}
#define SET_BOOL(name) void set##name(bool name) {name##_ = name;}
#define GET_SET_BOOL(name) GET_BOOL(name) SET_BOOL(name)
于 2013-03-15T23:34:03.040 回答
0

C/C++ does not support anything like this by default, however it is commonplace to have functions such as int getHP() and void setHP(int) but there is kind of an operator 'hack' to make it function pretty close to how c#'s get/set works. But the code to work around this is very messy and can cause many bugs.

Example (2nd post): http://forums.codeguru.com/showthread.php?459696-GET-SET-in-C

于 2013-03-15T23:34:19.443 回答