【发布时间】:2015-03-13 15:16:44
【问题描述】:
我目前正在学习 C++,我是一名经验丰富的 C# 和 Java 开发人员。
我有一个 B 类,其中包含 A 类的成员,我希望 B 类的用户能够更改 A 类中的值,但不能更改类的实例A 自己。
基本上它想阻止b.getA() = anotherA;被允许。
这在 c++ 中是否可行,还是我的设计在这里完全错误?
这是我的小 C++ 程序
#include <string>
#include <iostream>
using namespace std;
class A {
public:
string getName()
{
return name;
}
void setName(string value)
{
name = value;
}
private:
string name = "default";
};
class B {
public:
A &getA()
{
return anInstance;
}
private:
A anInstance;
};
int main(int argc, char** argv) {
B b;
cout << b.getA().getName() << std::endl; // outputs "default"
b.getA().setName("not default");
cout << b.getA().getName() << std::endl; // outputs "not default"
A a;
a.setName("another a instance");
b.getA() = a; // I want to prevent this being possible
cout << b.getA().getName() << std::endl; // outputs "another a instance"
}
我正在尝试做的 C# 示例
class Program
{
class A
{
private string name = "default";
public string getName()
{
return name;
}
public void setName(string value)
{
name = value;
}
}
class B
{
private A anInstance;
public A getA()
{
return anInstance;
}
}
static void Main(string[] args)
{
B b = new B();
Console.WriteLine(b.getA().getName()); // outputs "default"
b.getA().setName("not default");
Console.WriteLine(b.getA().getName()); // outputs "not default"
}
}
【问题讨论】:
-
你知道
const吗? -
string getName()应该是const string& getName() const(这只有在返回成员变量时才可以)和setName(string value)应该是setName(const string& value)这会减少字符串的副本。 -
他在问题中特别说“我希望B类的用户能够修改A类”。这不是关于 const,而是关于他的假设,即分配给调用者的引用也会改变 B 中的引用,但它不会。不要那么粗鲁和傲慢。
-
允许调用者修改 A 但不允许从另一个实例分配 A 是相当矛盾的,因为后者是前者的特例。您可以在 A 类上禁用
operator=。 -
@JfBeaulac 简而言之,
b.getA() = anotherA;并没有像你想象的那样做。
标签: c++ class reference getter