File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ #include " util.h"
2+ #include < iostream>
3+
4+ int main () {
5+ std::cout << " app=" << util::g_appName << " \n " ;
6+ std::cout << " g_counter=" << util::g_counter << " \n " ;
7+
8+ util::Greeter hi (" Hello" );
9+ std::cout << hi.greet (" Alice" ) << " \n " ;
10+
11+ hi.bump ();
12+ hi.bump ();
13+
14+ std::cout << " g_counter=" << util::g_counter << " \n " ;
15+ std::cout << " hi.localCount()=" << hi.localCount () << " \n " ;
16+ return 0 ;
17+ }
Original file line number Diff line number Diff line change 1+ #include " util.h"
2+ #include < utility> // std::move
3+
4+ namespace util {
5+
6+ // ===== 全局变量(定义,只能在一个 .cpp 中定义)=====
7+ int g_counter = 0 ;
8+ const std::string g_appName = " DemoApp" ;
9+
10+ // ===== 类实现 =====
11+ Greeter::Greeter (std::string prefix) : prefix_(std::move(prefix)) {}
12+
13+ std::string Greeter::greet (const std::string& name) const {
14+ return prefix_ + " , " + name + " !" ;
15+ }
16+
17+ void Greeter::bump () {
18+ ++g_counter;
19+ ++localCount_;
20+ }
21+
22+ int Greeter::localCount () const {
23+ return localCount_;
24+ }
25+
26+ } // namespace util
Original file line number Diff line number Diff line change 1+ #ifndef UTIL_H
2+ #define UTIL_H
3+
4+ #include < string>
5+
6+ namespace util {
7+
8+ // ===== 全局变量(声明)=====
9+ extern int g_counter;
10+ extern const std::string g_appName;
11+
12+ // ===== 类声明 =====
13+ class Greeter {
14+ public:
15+ explicit Greeter (std::string prefix);
16+
17+ std::string greet (const std::string& name) const ;
18+ void bump ();
19+ int localCount () const ;
20+
21+ private:
22+ std::string prefix_;
23+ int localCount_{0 };
24+ };
25+
26+ } // namespace util
27+
28+ #endif // UTIL_H
You can’t perform that action at this time.
0 commit comments