非法成员初始化 [英] Illegal Member initialization

查看:182
本文介绍了非法成员初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用这个简单的类而不使用任何继承。

  class A 
{
int a;
int b;

public:
A(int x,int y){a = x; b = y;}
A():A(0,0){};
〜A(){};
};

int main()
{
A a1,a2(5,7);
}

我收到此错误。


错误C2614:'A':非法成员初始化:'A'不是基础或成员



$ b b

有关SO的类似问题,但它们与继承有关。



p>如果有人在C ++ 11中更详细地阐述了转发构造函数和这个特性,最好。

解决方案

可以使用C ++ 11,可以从 A(int,int)初始化 A()。这是不可能在C ++ 03,你必须写两个单独的构造函数。



如果你想让你的代码在C ++ 03中工作,你有两个选项:




  • 创建一个函数 init(int,int)每个构造函数。这是一个很好的选择,如果你的构造函数做了很多工作。

  • 在两个构造函数中重复的行为。



您也可以从子类构造函数中调用基本构造函数。例如,如果您有

  class A {
A(int,int);
};
class B:public A {
B(int,int);
};

您可以写

  B :: B(int x,int y):A(x,y){} 

这是你的编译器所说的 A不是一个基础,它是期待这种情况。



所有这些都与C ++ 03兼容。



您还可以升级您的编译器以支持C ++ 11功能。我不推荐这个,如果你在Linux工作,并希望你的项目在Windows中编译,因为Windows编译器不实现所有的C ++功能,Linux编译器做(除非你支付一个好的编译器)。


I am using this pretty simple class without using any inheritance.

class A
{
  int a;
  int b;

public:
 A(int x, int y) { a = x; b = y;}
 A() :A(0,0){};
 ~A(){};
} ;

int main ()
{
  A a1, a2(5, 7) ;
}

I get this error.

error C2614: 'A' : illegal member initialization: 'A' is not a base or member

There are similar questions on SO but they relate to inheritance. Can someone explain the reason and what does standard say about that?

EDIT:

It would be better if someone elaborate more on the forwarding constructor and this feature in C++11.

解决方案

If you can use C++11, you could initialize A() from A(int, int). This is not possible in C++03, where you have to write two separate constructors.

If you want your code to work in C++03, you have two options:

  • Create a function init(int, int) and call it from each of your constructors. This is a good choice if your constructor does a lot of work.
  • Duplicate behaviour in both constructors. This is a good choice when all you are doing are member initializations.

You can also call a base constructor from a child class constructor. For instance, if you have

class A {
    A(int, int);
};
class B : public A {
    B(int, int);
};

You could write

B::B(int x, int y) : A(x,y) {}

This is what your compiler means when it says that A is not a base, it is expecting this situation.

All of these are compatible with C++03.

You could also upgrade your compiler to support C++11 features. I wouldn't recommend this if you are working in Linux and want your project to compile in Windows because Windows compilers don't implement all the C++ features that Linux compilers do (unless you pay for a good compiler).

这篇关于非法成员初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆