相关疑难解决方法(0)

对静态类成员的未定义引用

谁能解释为什么以下代码无法编译?至少在g ++ 4.2.4上.

更有趣的是,为什么它会在我将MEMBER转换为int时进行编译?

#include <vector>

class Foo {  
public:  
    static const int MEMBER = 1;  
};

int main(){  
    vector<int> v;  
    v.push_back( Foo::MEMBER );       // undefined reference to `Foo::MEMBER'
    v.push_back( (int) Foo::MEMBER ); // OK  
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

c++ g++

191
推荐指数
5
解决办法
11万
查看次数

如何隐藏除T类之外的所有人的数据

我想要一个类型A,它将隐藏的数据输出到类型为T的对象,但是隐藏其他人的数据.我的C++编译器碰巧是GCC 4.4,但这并不重要.为什么这不起作用?

#include <iostream>

template <class T> class A {
  private:
    int n1;
  public:
    friend class T;
    A(const int n0 = 0) : n1(n0) {}
};

class B {
  public:
    int f(const A<B> a) const { return a.n1; }
    B() {}
};

int main() {
    const A<B> a(5);
    const B b;
    const int m = b.f(a);
    std::cout << m << "\n";
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

顺便说一下,这样可以正常工作,除了它无法隐藏数据:

#include <iostream>

template <class T> class A {
  private:
    int n1; …
Run Code Online (Sandbox Code Playgroud)

c++ templates information-hiding friend access-protection

5
推荐指数
1
解决办法
216
查看次数