c++ - 我构造子类对象的方式有什么问题?

标签 c++ class inheritance mfc

这是我的子类:

class BackGround :public Object{
public:
BackGround(int y){
    character.Load(_T("wallpaper.png"));
    x = 0;
    this->y = y;
    direct = 0;
    width = 1200;
    height = 375;
}
};

我的基类:

class Object{
public:
CImage character;     
int x;             
int y;
int direct;       
int speed;
int width;      
int height;
int Xcenter;
int Ycenter;

Object(){}

void draw(HDC hDC){
    character.Draw(hDC, x, y, width, height, 0, direct*height,width, height);
}
};

当我创建 BackGround 类的对象时, 背景 Bg1(0); 背景 Bg2(-WINDOW_HEIGHT);

出现错误:

1>  MainFrm.cpp
1>c:\users\desktop\mfcgame\mfcgame\childview.h(46): error C2059: syntax error: 'const'
1>c:\users\desktop\mfcgame\mfcgame\childview.h(47): error C2059: syntax error:“-”
1>  MFCGame.cpp
1>c:\users\desktop\mfcgame\mfcgame\childview.h(46): error C2059: syntax error: 'const'
1>c:\users\desktop\mfcgame\mfcgame\childview.h(47): error C2059: syntax error:“-”
1>  ChildView.cpp
1>c:\users\desktop\mfcgame\mfcgame\childview.h(46): error C2059: syntax error: 'const'
1>c:\users\desktop\mfcgame\mfcgame\childview.h(47): error C2059: syntax error:“-”
1>c:\users\desktop\mfcgame\mfcgame\childview.cpp(67): error C2228: left of '.draw' must have class/struct/union type
1>c:\users\desktop\mfcgame\mfcgame\childview.cpp(68): error C2228: left of '.draw' must have class/struct/union type
1>c:\users\desktop\mfcgame\mfcgame\childview.cpp(116): error C2228: left of '.y' must have class/struct/union type
1>c:\users\desktop\mfcgame\mfcgame\childview.cpp(118): error C2228: left of '.y' must have class/struct/union type
1>c:\users\desktop\mfcgame\mfcgame\childview.cpp(120): error C2228: left of '.y' must have class/struct/union type
1>c:\users\desktop\mfcgame\mfcgame\childview.cpp(122): error C2228: left of '.y' must have class/struct/union type

最佳答案

我觉得你有

class CChildView : public CWnd
{
    // ...
    BackGround Bg1(0);                // Line 46
    BackGround Bg2(-WINDOW_HEIGHT);   // Line 47
};

这是声明成员变量的错误语法。
(编译器认为这些看起来像是成员函数的声明。)

如果你使用的是 C++11,你可以这样写

class CChildView : public CWnd
{
    // ...
    BackGround Bg1 {0}; 
    BackGround Bg2 {-WINDOW_HEIGHT};
};

用花括号,或者你可以初始化构造函数的初始化列表中的成员,这适用于所有 C++ 版本:

class CChildView : public CWnd
{
    CChildView();
    // ...
    BackGround Bg1; 
    BackGround Bg2;
};

// ... 

CChildView::CChildView() : Bg1(0), Bg2(-WINDOW_HEIGHT)
{
    // ...
}

关于c++ - 我构造子类对象的方式有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40957807/

相关文章:

java - NSMutableArray 中的类类型

swift - 覆盖 Swift 子类中的属性

c++ - 超过 8 个元素的动态数组崩溃

c# - C# 程序如何使用任何版本的 C++ dll?

c++ - 带智能指针的多态性

python - 从实例而不是类继承 [Python 3]

c# - 为不同数据库之间的共享功能创建通用/抽象 "DBContext"类

c++ - 返回对 const 引用参数的 const 引用

c++ - 全局静态对象销毁后,是否有可能调用OS计时器回调?

javascript - 将 $.getJSON 的结果传递给同一个类的另一个方法