在C ++中,有时最好在头文件中声明类并在cpp文件中定义所有方法。我理解这一点,但是这样做的结果似乎是,它们不是将所有的类方法都放在大括号内,而是直接在cpp文件中打开。 有没有办法在cpp文件中将类的方法组合在一起,同时仍在头文件中声明它们?我希望能够在我的IDE中折叠内容……我会克服它,但是已经有一段时间了,因为我已经用C ++编写了任何代码,而且我想知道是否有一种我忘了的方法。
为了清楚我的意思,这是一个例子:
test.h:
class Testing {
public:
Testing(int x);
void print();
int x;
};
test.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();
}
我想改用test.cpp中上面评论的内容,但这不起作用,对吗? (我想这就像在头文件中声明一个新类一样?)
您可以这样做:
namespace H_DEFS {
class H {
public:
int A();
int B();
};
}
namespace H_DEFS {
int H::A() { return 4;};
int H::B() { return 5;};
}
using namespace H_DEFS;
int main() {
return H().A() + H().B();
}
但是对于其他程序员来说,仅出于IDE的利益而阅读这是一个奇怪的习惯。