C++ - How to make read only class member variables in Visual Studio 2010
嗨,我正在尝试使一些公共成员变量为只读。 我知道我可以做类似的事情:
1 2 3 | private: int _x; public: const int& x; Constructor(): x(_x) {} |
我正在寻找更易于管理且更易于阅读的内容。 我在互联网上发现了几个模板,这些模板的作用与该SO答案中描述的代理类相似。
我正在尝试修改该代理类,以便可以将模板放在包含中,并为类中的每个变量编写类似的内容,而我只需要读取以下变量:
1 | public: proxy<int, myClass> num; |
如果我不必每次都说类名,但除非在模板中标识了类名,否则我不知道解决该问题的方法,这甚至会更容易。
我曾在Visual Studio 2010中尝试过此方法,但是它不起作用,有人知道为什么吗?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | template <class T, class C> class proxy { friend class C; private: T data; T operator=(const T& arg) { data = arg; return data; } public: operator const T&() const { return data; } }; class myClass { public: proxy<int,myClass> x; public: void f(int i) { x = i; } }; |
谢谢
编辑-有人问我的意思是行不通的:
1 2 3 4 5 6 7 | int main(int argc, char **argv) { myClass test; test.f(12); cout << test.x << endl; return 0; } |
返回:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | b.cpp(122) : error C2649: 'typename' : is not a 'class' b.cpp(128) : see reference to class template instantiation 'proxy<T,C>' being compiled b.cpp(136) : error C2248: 'proxy<T,C>::operator =' : cannot access private membe r declared in class 'proxy<T,C>' with [ T=int, C=myClass ] b.cpp(125) : see declaration of 'proxy<T,C>::operator =' with [ T=int, C=myClass ] |
更改此:
1 2 3 | template <class T, class C> class proxy { friend class C; |
对此:
1 2 3 | template <class T, class C> class proxy { friend C; |
因为
我认为您的问题出在设计上。 您不需要封装违反的"公共"成员。 我认为您正在寻找类似IoC的产品,请看一下访客模式,它可以为您提供帮助:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | class IStateHandler{ public: virtual void handleState( const proxy<int, myClass>& num )=0; virtual ~IStateHandler(){} }; class myClass { private: proxy<int,myClass> x; public: void f(int i) { x = i; } void handleState( IStateHandler* stateHandler ){ stateHandler->handle( x ); } }; |