C++ 常见错误收集

两个C++编译错误及解决办法--does not name a type和field `XX' has incomplete type

编译错误一:XX does not name a type

编译错误二:field `XX' has incomplete type

 

编译错误一:XX does not name a type, 中文意思为“XX没有命名一个类型“

拿个例子来讲,如果两个类定义如下:

class B{

public:

B(){}

~B(){}

private:

A a;

};

class A{

public:

A(){}

~A(){}

private:

int a;

};

编译成则将报一个error:"A does not name a type"

报错的位置为红色那一行。

即使clase A和class B分别在两个文件定义,并且在定义B的文件头中#include了class A的头文件也同样会报这个错(这是因为编译和链接之间的先后关系造成的)。

解决该错误的办法:

在class B定义声明之前先声明一下class A, 如下:

class A;

class B{

public:

B(){}

~B(){}

private:

A a;

};

class A{

public:

A(){}

~A(){}

private:

int a;

};

 

编译错误二:field `XX' has incomplete type

同样紧跟上面的例子,通过问题一的办法,第一个错误已经消失,但是马上第二个错误就出现了!还是同一个位置。

这个错误的意思,就是说class B中的XX域的类型不够完整,为什么呢?明明class A后面已经定义好了啊。其实原因还是和前面一样,在class B定义之前,我们也只是对class A进行了声明而并没有进行具体的定义,所以解决该错误的方法是:

将class B定义中的A域改用指针就行了。改正后代码为:

class A;

class B{

public:

B(){}

~B(){}

private:

A *a;

};

class A{

public:

A(){}

~A(){}

private:

int a;

};

这样,这段简单的代码才能没有错误的通过编译。



C++: "Cannot call member function without object"?

I get the following error when I try to compile my code in Code::Blocks:
"cannot call member function `std::string Battle::GetAnimationName()' without object|"

This is my code:
class Game
{
public:
···// some other variables and functions
···void PlayAnimation(string animation = GetAnimationName()) {
······// the rest of the function is redundant
···}

private:
···string GetAnimationName() {
······string animation;
······// algorithm that changes the value of 'animation'
······return animation;
···}
};

I can't figure out what the problem is.

Additional Details

@MJordan1: Nope, doesn't work. It tells me that "`this' may not be used in this context". (I copy pasted your code.)

2 years ago

  by Black Rose
Member since:
October 13, 2006
Total points:
6,402 (Level 5)

Best Answer - Chosen by Voters

EDITED:

define function GetAnimationName() as static function so that you can call it without need object.

// static string GetAnimationName() {
  • 2 years ago

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值