Mav*_*447 0 c++ constructor struct destructor
当我编译这个时,我收到编译错误和警告。
#include <iostream>
struct {
uint8_t m_data;
int size;
} BufferCustom;
class MyClass
{
private:
int x, y;
const int CONST_BUFFER_SIZE = 10;
struct BufferCustom *m_BufferPtr;
public:
MyClass(int xx, int yy) : x(xx), y(yy)
{
m_BufferPtr = new struct BufferCustom[CONST_BUFFER_SIZE];
}
virtual ~MyClass() {
if (m_BufferPtr){
delete [] m_BufferPtr;
m_BufferPtr = nullptr;
}
}
// user defined copy constructor
MyClass(const MyClass& rhs)
: x{ rhs.x }, y{ rhs.y } // initialize members with other object's // members
{
std::cout << "User defined copy constructor invoked.";
//m_BufferPtr = new struct B
}
MyClass& operator=(const MyClass &rhs)
{
std::cout << "Assignment operator called\n";
return *this;
}
};
int main()
{
MyClass o1{ 1, 2 };
MyClass o2 = o1; // user defined copy constructor invoked
o2 = o1;
}
Run Code Online (Sandbox Code Playgroud)
错误在这些行中:
MyClass(int xx, int yy) : x(xx), y(yy)
{
m_BufferPtr = new struct BufferCustom[CONST_BUFFER_SIZE];
}
Run Code Online (Sandbox Code Playgroud)
编译错误是分配不完整类型结构 BufferCustom
if (m_BufferPtr){
delete [] m_BufferPtr;
m_BufferPtr = nullptr;
}
Run Code Online (Sandbox Code Playgroud)
说删除指向不完整类型“struct BufferCustom”的指针可能会导致未定义的行为
我很困惑为什么这是一个错误!
这:
struct {
uint8_t m_data;
int size;
} BufferCustom;
Run Code Online (Sandbox Code Playgroud)
...定义一个具有匿名类型的结构,然后定义该类型的一个名为 的实例BufferCustom。BufferCustom没有名称的类型的单个变量也是如此。
但是您后来的代码尝试将BufferCustom其视为类型的名称。我猜你的意图是这样的:
struct BufferCustom {
uint8_t m_data;
int size;
};
Run Code Online (Sandbox Code Playgroud)
这定义为类型BufferCustom的名称,以便您稍后可以分配该类型的对象。BufferCustom
| 归档时间: |
|
| 查看次数: |
42 次 |
| 最近记录: |