簡體   English   中英

C++ 中的組合語法

[英]Composition syntax in C++

我正忙於使用 C++ 中的組合和類。 我遇到的一個代碼片段以以下方式實現組合:

#include<iostream>
using namespace std;
class Engine {
  public:
    int power;
};
class Car {
  public:
    Engine e;
    string company;
    string color;
    void show_details() {
      cout << "Compnay is:            " << company << endl;
      cout << "Color is:              " << color   << endl;
      cout << "Engine horse power is: " << e.power << endl;
    }
};
int main() {
  Car c;
  c.e.power = 500;
  c.company = "hyundai";
  c.color   = "black";
  c.show_details();
  return 0;
}

這編譯得很好,並運行。 我不喜歡這個實現的一件事是函數“void show_details”的實際位置,我更願意把它放在外面。

但是,如果我天真地嘗試執行以下操作:

#include<iostream>
using namespace std;
class Engine {
  public:
    int power;
};
class Car {
  public:
  //Engine e;
    string company;
    string color;
    void show_details();
  //void show_details() {
  //  cout << "Compnay is:            " << company << endl;
  //  cout << "Color is:              " << color   << endl;
  //  cout << "Engine horse power is: " << e.power << endl;
  //}
};
void Car::show_details(){
  cout << "Compnay is:            " << company << endl;
  cout << "Color is:              " << color   << endl;
  cout << "Engine horse power is: " << e.power << endl;
}
int main() {
  Car c;
  c.e.power = 500;
  c.company = "hyundai";
  c.color   = "black";
  c.show_details();
  return 0;
}

g++ 返回以下錯誤:

comp3.cpp: In member function ‘void Car::show_details()’:
comp3.cpp:22:44: error: ‘e’ was not declared in this scope
       cout << "Engine horse power is: " << e.power << endl;
                                            ^
comp3.cpp: In function ‘int main()’:
comp3.cpp:26:9: error: ‘class Car’ has no member named ‘e’
      c.e.power = 500;

我顯然對范圍界定問題感到困惑,但我不確定缺失的部分是什么。

感謝您的任何幫助!

在第二個示例中,您注釋掉了e

//Engine e;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM