gpt4 book ai didi

c++ - 定义未命名的类成员函数?

转载 作者:太空狗 更新时间:2023-10-29 23:01:47 25 4
gpt4 key购买 nike

我目前在我的 Foo.h 中定义了两个未命名的类:

class Foo {
public:
Foo();

class {
private:
int x;
int y;
public:
int GetX() { return x; }
int GetY() { return y; }
} Sub1;

class {
private:
int x;
public:
int GetX() { return x; }
} Sub2;
}

这段代码编译得很好,它是这样使用的:

 Foo temp;
int Ax, Ay, Bx;
Ax = temp.Sub1.GetX();
Ay = temp.Sub1.GetY();
Bx = temp.Sub2.GetX();

但是,现在我想将成员函数定义移动到源文件中。我知道将此类拆分为头文件和源文件的唯一方法是命名类:

Foo.h:

class Foo {

private:
class A {
private:
int x;
int y;
public:
int GetX();
int GetY();
};

class B {
private:
int x;
public:
int GetX();
};

public:
Foo();
A Sub1;
B Sub2;

}

Foo.cpp:

int Foo::A::GetX() { return x; }
int Foo::A::GetY() { return y; }
int Foo::B::GetX() { return x; }

但是,这段代码不是我想要的,因为它很丑陋,而且我一开始就不想使用命名类。

是否可以将类拆分为头文件和源文件?或者这只是糟糕的代码设计?

最佳答案

不幸的是,这是不可能的。 §9.3/5:

If the definition of a member function is lexically outside its class definition, the member function name shall be qualified by its class name using the :: operator.

由于不存在类名,因此成员函数的类外定义是不可能的。 GCC 在此上下文中允许 decltype-specifiers 的事实是一个错误。

关于c++ - 定义未命名的类成员函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30354130/

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