指定方法不修改Typescript中的类?
我希望能够传递一个不可变的(或类似的) 这使得创建对象的不可变或只读引用变得很容易。有些用户可以改变对象。其他用户获得对该对象的指定方法不修改Typescript中的类?,typescript,Typescript,我希望能够传递一个不可变的(或类似的) 这使得创建对象的不可变或只读引用变得很容易。有些用户可以改变对象。其他用户获得对该对象的const&引用,并且不能改变该对象 struct A { int x; int get() const { return x; }; // this method does not mutate A void set(int newX) { x = newX; }; }; intmain(){ std::cout我认为最好的选择是创建一个只读接口,该接口
const&
引用,并且不能改变该对象
struct A {
int x;
int get() const { return x; }; // this method does not mutate A
void set(int newX) { x = newX; };
};
intmain(){
std::cout我认为最好的选择是创建一个只读接口,该接口没有set
方法。a
将实现该接口
int main() {
std::cout << "Hello World!\n";
A a;
a.get();
a.set(4);
A const & constA = a;
constA.get();
constA.set(4); // THIS IS ILLEGAL
}
然后像这样使用它:
interface IA {
get();
}
@尾声我不确定该代码会禁止你。谢谢!(我之前的评论还没有结束:)
int main() {
std::cout << "Hello World!\n";
A a;
a.get();
a.set(4);
A const & constA = a;
constA.get();
constA.set(4); // THIS IS ILLEGAL
}
interface IA {
get();
}
const a: IA = new A()