简体   繁体   English

C++ Class 方法定义语法

[英]C++ Class Methods Definition Syntax

In C++, it is sometimes considered good practice to declare your classes in a header file and define all the methods in a cpp file.在 C++ 中,有时认为在 header 文件中声明您的类并在 cpp 文件中定义所有方法是一种很好的做法。 I understand this, but a consequence of this seems to be that instead of having all of the class methods tabbed-in inside curly braces, they are just out in the open in the cpp file.我理解这一点,但这样做的结果似乎是,不是将所有 class 方法都放在花括号内,而是在 cpp 文件中打开。 Is there any way to group the methods of a class together in the cpp file while still declaring them in a header file?有什么方法可以在 cpp 文件中将 class 的方法组合在一起,同时仍然在 header 文件中声明它们? I like being able to collapse things in my IDE... I'd just get over it, but it's been a while since I've coded anything in C++ and I'm wondering if there's a way to do it that I just forgot about.我喜欢能够在我的 IDE 中折叠东西......我会克服它,但我已经有一段时间没有在 C++ 中编写任何东西了,我想知道是否有办法做到这一点,我只是忘记了关于。

To be clear what I mean, here's an example:为了清楚我的意思,这里有一个例子:

test.h:测试.h:

class Testing {
public:
    Testing(int x);
    void print();
    int x;
};

test.cpp:测试.cpp:

#include <iostream>
#include "test.h"

using namespace std;

// class Testing {
// public:
//     Testing(int x){
//         this->x = x;
//     }

//     void print(){
//         cout << this->x << endl;
//     }
// };

Testing::Testing(int x){
    this-> x = x;
}

void Testing::print(){
    cout << this->x;
}

int main(){
    Testing t(100);
    t.print();
}

I'd like to do what is commented above in test.cpp instead, but that doesn't work, right?我想做上面在 test.cpp 中评论的内容,但这不起作用,对吧? (I think it'd be like declaring a new class distinct from the one in the header file?) (我认为这就像声明一个新的 class 不同于 header 文件中的那个?)

You could do this:你可以这样做:

== hh == == 哈哈 ==

namespace H_DEFS {
    class H {
    public:
       int A();
       int B();
    };
}
using namespace H_DEFS;

== h.cpp file == == h.cpp 文件 ==

#include "h.h"
namespace H_DEFS {
   int H::A() { return 4;};
   int H::B() { return 5;};
}

== main.cpp == == main.cpp ==

#include "h.h"
int main() {
   return H().A() + H().B();
}

but it's a weird idiom for other programmers to read just for the benefit of your IDE.但是对于其他程序员来说,为了您的 IDE 的利益而阅读它是一个奇怪的习惯用法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM