简体   繁体   中英

why cant my c++ code show cout string

this is my main.cpp

#include <iostream>
using namespace std;
#include "test.h"

void main()
{
    Solution aa;
    aa.aaa();

    cin.get();
}

this is my test.h

#pragma once

class Solution {
public:
    void aaa() {};
};

this is my test.cpp

#include <iostream>

using namespace std;

class Solution {
public:  

    void aaa() {
        cout << "aaaaa" << endl;
    };
};

and when I run the c++ code, it shows nothing. Can anybody tell me why?

Your test.h declared and defined a Solution class, with an aaa() class method that does absolutely nothing.

 void aaa() {};

See, the aaa() method does nothing.

Your main() called this method, that does absolutely nothing.

End result: nothing happened, as expected.

You also happened to have a test.cpp that happened to declare and define its own class, of the same name. At the very least, this is undefined behavior, and I would point my finger and laugh at any C++ compiler+linker that decided that there was nothing wrong with linking together both main.cpp and test.cpp .

In test.h:

void aaa() {};

Notice that you put empty brackets instead of just a semicolon after the (). If you want to write a function declaration you just write the function name and parameters but not the brackets. Now the compiler thinks that you want to write a function that does nothing. (I'm surprised that this didn't cause a linking error)

Your test.h and test.cpp files are implemented incorrectly. They should look more like this instead:

test.h

#pragma once

class Solution {
public:
    void aaa();
};

test.cpp

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

using namespace std;

void Solution::aaa() {
    cout << "aaaaa" << endl;
}

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