如何在 C++ 中的 .h 文件中的 class 中定义结构
How to define a struct inside a class inside a .h file in C++
我正在尝试在 .h 文件内的 class 内添加一个结构,而我到现在为止想到的是:
//Rectangle.h
#pragma once
#include <bits/stdc++.h>
using namespace std;
class Rectangle
{
public:
Rectangle() ;
struct recpoints
{
double x1, y1, x2, y2, x3, y3, x4, y4;
};
};
// Rectangle.cpp
#include "Rectangle.h"
Rectangle::Rectangle() {}
Rectangle::recpoints
{
recpoints() { x1 = y1 = x2 = y2 = x3 = y3 = x4 = y4 = 0.0; }
};
现在代码会产生错误
g++ -c main.cpp Rectangle.cpp
Rectangle.cpp:5:5: error: expected unqualified-id before ‘{’ token
而且我不知道该如何修复它以及如何使用 Rectangle.cpp 文件中的结构?
- 您忘记在 header 中的
struct recpoints
内部声明构造函数 recpoints()
。
recpoints()
的定义应该是Rectangle::recpoints::recpoints() { /*your code here*/ }
(不包含在Rectangle::recpoints{...};
中)。
我正在尝试在 .h 文件内的 class 内添加一个结构,而我到现在为止想到的是:
//Rectangle.h
#pragma once
#include <bits/stdc++.h>
using namespace std;
class Rectangle
{
public:
Rectangle() ;
struct recpoints
{
double x1, y1, x2, y2, x3, y3, x4, y4;
};
};
// Rectangle.cpp
#include "Rectangle.h"
Rectangle::Rectangle() {}
Rectangle::recpoints
{
recpoints() { x1 = y1 = x2 = y2 = x3 = y3 = x4 = y4 = 0.0; }
};
现在代码会产生错误
g++ -c main.cpp Rectangle.cpp
Rectangle.cpp:5:5: error: expected unqualified-id before ‘{’ token
而且我不知道该如何修复它以及如何使用 Rectangle.cpp 文件中的结构?
- 您忘记在 header 中的
struct recpoints
内部声明构造函数recpoints()
。 recpoints()
的定义应该是Rectangle::recpoints::recpoints() { /*your code here*/ }
(不包含在Rectangle::recpoints{...};
中)。