【发布时间】:2013-11-09 00:28:21
【问题描述】:
我学了一点 C#,现在我正在学习 C++。在 C# 中,数据隐藏可以使用 get 和 set 运算符来完成,通过提供“get”而不是“set”,可以将数据成员呈现为“只读”。
这将允许一个类 (Person) 包含另一个类 (Account),这样 Account 类的公共功能对 Person.Account 的用户可用,但用户不能直接更改 Account 类,因为它是只读的。
这应该在下面的代码示例中更清楚。
我的问题是,由于 C++ 不提供漂亮的 get/set 语法,是否有与下面代码类似的 C++?
using System;
class Person
{
private string _Name;
public string Name { get { return _Name; } set { _Name = value; } }
private Account _Account;
public Account Account { get { return _Account; } }
public Person()
{
_Name = "";
_Account = new Account();
}
}
class Account
{
private decimal _Balance;
public decimal Balance { get { return _Balance; } }
public Account()
{
_Balance = 0;
}
public void Deposit(decimal deposit)
{
_Balance += deposit;
}
}
class Program
{
static void Main(string[] args)
{
Person p = new Person();
p.Name = "John Doe";
// not allowed: p.Account = new Account();
// Property or indexer 'CSharp.Person.Account' cannot be assigned to -- it is read only
// allowed: the Account Object's public functions are available
p.Account.Deposit(1000);
Console.WriteLine(p.Account.Balance.ToString());
// console says "1000"
}
}
【问题讨论】:
-
请注意,标准禁止在用户代码中使用下划线和大写字母作为名称。请参阅 C++11 17.6.4.3.2 [global.names]/1:某些名称和函数签名集始终保留给实现:每个名称包含双下划线
_ _或以下划线开头,后跟大写字母 (2.12) 保留给实现以供任何使用。 -
注意到了。我正在尝试为 C++ 中的私有属性找到我喜欢的样式。我对 myAccount 不感兴趣,我更不喜欢 m_Account。 C++ 课的老师喜欢使用 myAccount、myPerson 等作为私有成员。
标签: c# c++ class object-oriented-analysis