【问题标题】:C++ - How to make read only class member variables in Visual Studio 2010C++ - 如何在 Visual Studio 2010 中制作只读类成员变量
【发布时间】:2012-08-27 16:21:16
【问题描述】:

您好,我正在尝试将一些公共成员变量设为只读。我知道我可以这样做:

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


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

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

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
        ]

【问题讨论】:

  • 所以您是说模板比const 更易于管理和阅读?
  • 告诉我们“它不起作用”是什么意思
  • @Luchian 一点也不。我需要一些公开只读且私下没有相同限制的东西。 const 很棒,这不是我在这里寻找的。如果我使用前者,在我的所有类函数中我必须附加一个前缀,并且有很多变量可以做到这一点。我认为这只会导致更丑陋的代码。
  • @Drew 好的我更新了我的问题以显示 CL 的输出
  • @test - 这很有帮助。错误消息告诉您,您在第 122、128 和 136 行遇到了特定问题。您能评论一下是哪几行吗?

标签: c++ class constructor constants readonly


【解决方案1】:

改变这个:

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

到这里:

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

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

【讨论】:

  • 谢谢。我刚刚尝试代理一些字符串变量,我注意到如果我有类似proxy&lt;string,myClass&gt; str 的东西,并且我尝试将 str 传递给一个接受字符串引用的函数,编译器将使用cannot convert parameter 1 from 'proxy&lt;T,C&gt;' to 'std::string &amp;' 出错。你知道我在那里做错了吗?
  • @test:您希望在 proxy 类模板中使用私有非 const operator T&amp;() { return data; } 以允许 myClass 将代理转换为对 T 的非 const 引用。
  • @Oktalist 我试过了,但后来我无法再公开访问 test.x:error C2248: 'proxy&lt;T,C&gt;::operator int &amp;' : cannot access private member declared in class 'proxy&lt;T,C&gt;'
【解决方案2】:

我认为您的问题出在设计上。您不需要违反封装的“公共”成员。我认为您正在寻找 IoC 之类的东西,看看访问者模式它可以帮助您:

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

};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-22
    • 2011-06-05
    • 2014-11-21
    • 2021-07-22
    • 2011-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多