C++ - 如何在 Visual Studio 2010 中创建只读类成员变量

标签 c++ class constructor constants readonly

您好,我正在尝试将一些公共(public)成员变量设置为只读。我知道我可以做类似的事情:

private: int _x;
public: const int& x;
Constructor(): x(_x) {}


我正在寻找更易于管理和更易于阅读的东西。我在互联网上找到了几个模板,所有这些模板都类似于 this 中描述的代理类。所以回答。

我正在尝试调整该代理类,以便我可以将模板放在一个包含中,并为我需要只读变量的类中的每个变量编写类似这样的内容:

public: proxy<int, myClass> num;

如果我不必每次都说出类名,那就更容易了,但我不知道如何解决这个问题,除非在模板中标识了类名。

我在 Visual Studio 2010 中试过这个但它不起作用,有人知道为什么吗?

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;
    }
};

谢谢

编辑 - 有人问我的意思是行不通:

int main(int argc, char **argv)
{
    myClass test;
    test.f(12);
    cout << test.x << endl;
    return 0;
}

返回:

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
        ]

最佳答案

改变这个:

template <class T, class C>
class proxy {
  friend class C;

为此:

template <class T, class C>
class proxy {
   friend C;

因为 C 是模板参数,所以不能保证 C 一定是类类型。

关于C++ - 如何在 Visual Studio 2010 中创建只读类成员变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12239229/

相关文章:

c++ - 这个构造函数做什么?

java - 当没有传递参数时,我应该在构造函数中使用关键字 "this"吗?

java存储实例变量并使用键值之一进行访问

c# - 基本构造函数未被调用

c++程序突然停止写入文件

c++ - 为什么我们不能使函数显式化?

c++: ptr_fun() 错误信息

c++ - 基于类的状态机?

vba - VBA 类中的 Let 和 Get 属性

class - 有没有更好的方法使用 Ext.apply 将子/子对象组合到另一个对象中?