C++:它是如何工作的别名成员类



在以下代码中:

class prova: public std::map< int,int >
{
 public:
 prova():a(5){}
 int a;
};
int main()
{
 std::vector<prova> p;
 prova obj;
 p.push_back(obj); 
 return 0;
}

它工作起来没有问题;如果我添加一个参考成员

class prova: public std::map< int,int >
{
 public:
 prova():a(5){}
 int a;
 int& b=a;
};
int main()
{
 std::vector<prova> p;
 prova obj;
 p.push_back(obj); 
 return 0;
}

我有

warning: non-static data member initializers only     available with -std=c++11 or -std=gnu++11 [enabled by default]|
/home/andrea/Scaricati/prova.cpp||In instantiation of ‘void 
std::vector<_Tp,_Alloc>::_M_insert_aux(std::vector<_Tp, _Alloc>::iterator, const _Tp&) 
[with _Tp = prova; _Alloc = std::allocator<prova>; 
std::vector<_Tp, _Alloc>::iterator = __gnu_cxx::__normal_iterator<prova*, std::vector<prova> >; typename std::_Vector_base<_Tp, _Alloc>::pointer = prova*]’:|
/usr/include/c++/4.8/bits/stl_vector.h|913|required from ‘void std::vector<_Tp, _Alloc>::push_back(const value_type&) [with _Tp = prova; _Alloc = std::allocator<prova>;   std::vector<_Tp, _Alloc>::value_type = prova]’|
/home/andrea/Scaricati/prova.cpp|19|required from here|
/home/andrea/Scaricati/prova.cpp|4|error: non-static reference member ‘int& prova::b’,     can’t use default assignment operator|
/usr/include/c++/4.8/bits/vector.tcc|335|note: synthesized method ‘prova&     prova::operator=(const prova&)’ first required here     
|||=== Build failed: 1 error(s), 4 warning(s) (0 minute(s), 0 second(s)) ===|

添加-std=g++11没有问题,就像警告中建议的那样。如果我删除矢量声明,我只得到了没有错误的警告。为什么C++旧标准不能做到这一点?references属性有什么问题?有没有一个系统可以在不使用c++11标准的情况下做同样的事情?我尝试

class prova: public std::map< int,int >
{
 public:
 prova():a(5),b(a){}
 int a;
 int &b;
};

但是我会出错。为什么这样?谢谢

您会收到警告,因为您的编译器足够聪明,能够了解C++11的语法。在C++中,这种语法int& b= a被称为In class member initializer,而在以前的标准中,这只能用static const变量来完成。C++11放宽了这些限制。

来自Stroustrup的页面:

在C++98中,只有积分类型的static const成员可以在类中初始化,并且初始值设定项必须是常量表示这些限制确保我们能够编译时的初始化。

例如:

int var = 7;
class X {       
    static const int m1 = 7;        // ok       
    const int m2 = 7;               // error: not static        
    static int m3 = 7;              // error: not const         
    static const int m4 = var;      // error: initializer not constant expression 
    static const string m5 = "odd"; // error: not integral type         
    // ...  
}; 

C++11的基本思想是允许非静态数据成员在声明它的位置(在它的类中)初始化。构造函数可以然后在需要运行时初始化时使用初始化器。考虑:

class A {   
public: 
    int a = 7;  
};

这相当于:

class A {   
public:         
    int a;      
    A() : a(7) {}   
};

最新更新