简体   繁体   中英

Composition syntax in C++

I am in the middle of getting my feet wet with the use of composition & classes in C++. A code snippet I came across implements composition in the following manner:

#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;
}

This compiles fine, and runs. One thing I do not like about this implementation is the actual location of the function "void show_details", which I would prefer to place outside.

However, if I naively try to do the following:

#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++ returns the following errors:

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;

I am clearly confused regarding issues of scoping, but I am not sure as to what the missing piece is.

Thanks for any & all help!!!

在第二个示例中,您注释掉了e

//Engine e;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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