C++二进制范围解析运算符和类

发布于 2024-10-06 01:45:49 字数 754 浏览 12 评论 0原文

有没有办法在 C++ 中使用“块”类作用域解析,这样我就不必为类实现文件中的每个函数编写相同的样板代码。

我发现在 C++ 的头文件之外定义函数时,编写相同的类名和二进制作用域解析运算符 (Classname::) 极其重复。

在 Objective-C 中,我只需要在 @implementation/@end 块中包含函数。

Objective-C 示例:

// Buttons.h
@interface Buttons : UIView {
    NSMutableArray *buttonArray;
}
- (int)getNumberButtons;

// Buttons.m
#import "Buttons.h"
@implementation 
- (int)getNumberButtons 
{
    return [buttonArray count];
}
@end // End implemenation

C++ 示例

// Buttons.h
class Buttons {
public:
    int getNumberOfButtons() const;
protected:
    std::vector<Button> buttons;
};
// Buttons.cpp
#include "Buttons.h"
int Buttons::getNumberOfButtons() const {
    return buttons.size();
}

Is there a way to use "block" class scope resolution in C++ so that I don't have to write the same boilerplate code for every function in my class' implementation file.

I find it extremely repetitive to write the same class name and binary scope resolution operator (Classname::) when defining a function outside of the header file in C++.

In Objective-C I only need to include functions within the @implementation/@end block.

Objective-C Example:

// Buttons.h
@interface Buttons : UIView {
    NSMutableArray *buttonArray;
}
- (int)getNumberButtons;

// Buttons.m
#import "Buttons.h"
@implementation 
- (int)getNumberButtons 
{
    return [buttonArray count];
}
@end // End implemenation

C++ Example

// Buttons.h
class Buttons {
public:
    int getNumberOfButtons() const;
protected:
    std::vector<Button> buttons;
};
// Buttons.cpp
#include "Buttons.h"
int Buttons::getNumberOfButtons() const {
    return buttons.size();
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

八巷 2024-10-13 01:45:49

不,除非您将其全部实现在类定义的标头中(您通常不应该这样做)。

从技术上讲,你可以用宏来破解它,但其他查看代码的人会因此讨厌你。您必须习惯这里的“C++ 方式”。

根据您使用的 IDE,通常有一些工具(例如 Visual Assist X for Visual Studio)可以帮助您从类定义生成一些样板文件。

No, unless you would implement it all in the header in the class definition (which you usually shouldn't).

Technically you could hack it with macros, but everyone else looking at the code would hate you for it. You'll have to get used to "the C++ way" here.

Depending on what IDE you work with, there are usually tools (e.g. Visual Assist X for Visual Studio) that help you generate some of the boilerplate from a class definition.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文