gpt4 book ai didi

C++ 成员类声明在一个文件中。在另一个实现

转载 作者:太空宇宙 更新时间:2023-11-04 11:25:13 25 4
gpt4 key购买 nike

我想知道我将在下面解释的过程是否被认为是标准的 c++ 98。

事实上,我有一个 A 类,它有一个名为 B 的私有(private)成员类。为了让一切更容易阅读和更符合逻辑,我想在 A.h 中声明我的 A 类,在 B.h 中声明我的 B 类。同样,我希望我的 A 类的实现在 A.cpp 中,而我的 B 类的实现在 B.cpp 中。

以下是我曾经在 VS2012 和 GCC 下编译(没有任何问题)的所有文件。出于可读性原因,我没有在此处的 .h 文件中包含包含保护程序。

预先感谢您的帮助。

---------------------------- A.h ------------------ --------------------------

class A
{
public:
A();
void printFromB();
void createB();
private:
class B;
B* b;
};

#include "B.h"

---------------------------- B.h ------------------ --------------------------

#include <iostream>

class A;

class A::B
{
public:
void print();
};

---------------------------- A.cpp ---------------- ------------------------------

#include "A.h"

A::A(){}

void A::printFromB() {
b->print();
}

void A::createB(){
b = new B;
}

---------------------------- B.cpp ---------------- ------------------------------

#include "A.h"

using namespace std;

void A::B::print()
{
cout << endl << "B prints!" << endl;
}

------------------------ main.cpp ---------------- --------------------------

#include "A.h"

int main()
{
A a;
a.createB();
a.printFromB();

return 0;
}

最佳答案

您的代码没有任何违法行为。

根据定义,如果没有class A,您永远不会使用class B

但是正是这个定义提出了一个问题,“那为什么还要创建一个单独的文件呢?”不过,由于这是您的项目,您可以按照自己的意愿进行。

关于C++ 成员类声明在一个文件中。在另一个实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26914202/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com