作者adrianshum (Alien)
看板C_and_CPP
标题Re: [语法] C#与bcb语法的转换
时间Fri May 22 14:52:25 2009
※ 引述《beebeecall (bee)》之铭言:
: 标题: [语法] C#与bcb语法的转换
: 时间: Fri May 22 11:58:35 2009
:
: 最近想练习一个 Decorator pattern的程式,
: 在网上参考了别人的作品,
: 他的语言是C#
: 内中写到
: public virtual string Description
: {
: get { return description; }
: set { description = value; }
: }
:
: 想请问这段程式码该怎麽改写,
: 就我微薄的程式能力来看,
: 这似乎是在定义Description这个变数,是吗?
: 很抱歉我基础打不好,所以问题可能很瞎,
: 但我真的很想学,麻烦知道的人帮忙解答罗。
:
发问不是问题, 但可不可以经过思考才定标题呢?
你整个例子里面, 和 decorator 的关系在哪?
你问的是 C# 的 property 通常在 C++ 会怎样表达.
: --
:
※ 发信站: 批踢踢实业坊(ptt.cc)
: ◆ From: 59.126.200.190
: 推 legnaleurc:就是 getter 和 setter ,别想太多 05/22 12:12
: → beebeecall:还是不会orz 05/22 13:10
: → stero: description =value 载入value的值之後回传description 05/22 13:14
: → stero:小弟猜是这样 05/22 13:15
: → Cloud:就 string getDescription(){return description;} 05/22 13:47
: → Cloud:void setDescription(string s){description = s;} 05/22 13:47
: → windincloud:楼上正解~ 05/22 14:07
通常不会这样写吧
getDescription 这样写会每次 return a copy of string.
一般来说会写
string& getDescription() {
return description;
};
吧?
另外这类 getter method 通常是 const method (当然, 还是要视乎情况)
const string& getDescription() const {
return m_description;
}
setter 通常传入obj 的话, 会传 const &, 省去 copy ctor 和建立一个新 obj
void setDescription(const string& s) {
m_description = s;
}
一般使用方便来说, 比较少会真的传入 std::string,
通常传入 char* 会比较方便:
void setDescription(const char* s) {
m_description = s; // m_description 当然是 std::string
}
Alien
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 202.155.236.82
1F:→ Cloud:这样写更好~~当然我只是提供个形式而已~~ 05/22 15:23
2F:推 beebeecall:感谢解答 顺便说明 我的标题没有提到decorator 05/22 15:34
3F:→ beebeecall:只是内文碎念提到因为看什麽碰到这问题 05/22 15:35
4F:→ adrianshum:咦咦? 对不起, 错怪了你, 是我眼花了 orz 05/22 17:03
5F:推 kvykn:alien是什麽? 05/22 18:49
6F:→ adrianshum:alien 是我的名字 orz 05/22 20:07
7F:→ adrianshum:习惯文章结尾都会署名.... 05/22 20:08