简体   繁体   中英

Using main.cpp and foo.cpp

I have a simple program I made for class and I found an example of a program using a

.h foo.cpp and main.cpp

I entered that program and got it to compile fine but when I move split mine up I cannot get it to compile.

What is the typical process for running methods in main from the other .cpp files?

Here is my current program that runs,

main.cpp

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

std::ostream& operator<<(std::ostream& s, const cars& c) {
    return s << c.make << ' ' << c.model  << ' ' <<  c.col << ' ' << c.wheels;
}

int main() {

    cars c("Audi", "A4", "Black", "4");
    cars q(c);

    std::cout << c << '\n';

    std::cout << q << '\n';

    return 0;
}

If I wanted to create a cars.cpp file and split it up so I just cout in main method what rules would I follow here?

For instance should I override in the main.cpp or should I move that to cars.cpp ?

I could obviously copy the other program I found but I want to understand this.

Also no this is not the assignment. I finished it I want to know how to do this because I am a Superhero who happens to love being ahead of everyone else.

Add

extern std::ostream& operator<<(std::ostream& s, const cars& c);

in cars.h .

Move the implementation,

std::ostream& operator<<(std::ostream& s, const cars& c) {
    return s << c.make << ' ' << c.model  << ' ' <<  c.col << ' ' << c.wheels;
}

to cars.cpp .

  1. Move the ostream operator in cars.cpp
  2. Add a declaration for it in cars.h
  3. Include iostream in cars.h

I assume cars.cpp includes cars.h already?

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